メインコンテンツへスキップ

Gemini Pro Gem メタ分析ダメダメソフト・フォレストプロット読み込み解析アプリ

    2026年2月8日追加:GemniのCanvas+高速モード(無料)

    コクランレビューで簡単なフォレストプロットぐらいならば、その図を添付して、GemniのCanvas+高速モード(無料)で「同じフォレストプロットを作成して感度分析と論文追加ができるようにして」のいい加減なプロンプトだけで、図のようなアプリができてしまいます。

    画像

    フォレストプロット読み込み解析アプリ

    以下の公開後に、論文のフォレストプロットを画像で保存。それをアップロードすると、論文ごとのデータを読み取って、再度、メタ分析を行うアプリを作りました。

    【重要】本アプリの使用目的について
    このアプリは、論文に掲載するような厳密なデータ解析用ではなく、EBMを実践・学習するためのシミュレーターです。
    「もし新しい研究結果が出たらどうなるか?」「このデータを除外するとどう変わるか?」といった分析を直感的に行い、EBMへの理解を深めるためにご活用ください。

    注意:gemini3.0proでのデータ読み込みなら、かなり精度が良いが、無料公開のためFlashにしている。よって、データ読み込みが失敗が多いです。その場合は、リロードして再度読み込むと成功することが多いです(観察研究の典型的でないフォレストプロットも意外と読み込めてびっくりです)。
    また、フォレストプロット上のサブグループ・トータルのメタ分析の結果を研究名と認識することがあるので、データのTypeをtotalなどに変えるか、その行を削除して下さい。

    注意:それでも、データ読み込みができない場合は、自分の課金している高性能のAIで、フォレストプロットをCSV形式に読み込ませてからアップしてください。


    フォレストプロット作成のアプリを自分で作ってみたら数週間で古いネタになってしまった。

    以下のコード利用より、「Vibe Coding(バイブ・コーディング)」と検索して、自分で作ることをお勧めします。上の2026/28の記事のような時代になっています。

    EBMの実践で、どうしても、フォレストプロットを自分で作って、論文を減らしたりの感度分析を行いたい時があります。以前はRebManでしたがWebになって面倒。オンラインのものもあるのですが、AIのが便利かな。

    画像
    こんな感じで、GeminiのPro用(無料では

    問題点は? 最初に言い訳・・・

    エラーが多いです。とりあえず、エラー修正のボタンを押すと何とかなるかな?だめなら、再度、Gemから立ち上げなおしてください。
    連続変数は、安定性のため別アプリですし、HRなどは使えません。まじん式と異なって、安定しておりません。プログラムの知識無しで、Geminiの壁打ちのみで作っています。
    個人的には、GeminiでRのメタ分析用のコードを書いてもらって、Rで解析のが、確実だが、、、AIで完結したいんだな。たぶん、数ヶ月後には、同じようなもっと素晴らしいのが出てくると思います。

    作成方法は? 動画が一番下にあります

    作成方法1:Gemのカスタム指示に以下のプロンプトを入れる

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Meta-Analysis Pro (Stable & Safe)</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js"></script>
        <script src="https://unpkg.com/lucide@latest"></script>
        
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Roboto+Mono:wght@400;500&display=swap');
            
            body { font-family: 'Inter', sans-serif; background-color: #f8fafc; color: #334155; }
            .font-mono { font-family: 'Roboto Mono', monospace; }
            
            /* Custom Scrollbar */
            .custom-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
            .custom-scroll::-webkit-scrollbar-track { background: transparent; }
            .custom-scroll::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
            .custom-scroll::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
    
            /* Status Messages */
            .msg-box { padding: 10px 14px; border-radius: 8px; margin-bottom: 12px; font-size: 13px; line-height: 1.5; display: flex; align-items: center; gap: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
            .error-msg { color: #991b1b; background: #fef2f2; border: 1px solid #fecaca; }
            .success-msg { color: #166534; background: #f0fdf4; border: 1px solid #bbf7d0; }
    
            /* Layout Utilities */
            .panel-container { display: flex; flex-direction: column; height: 100%; }
        </style>
    </head>
    <body class="h-screen flex flex-col overflow-hidden">
    
        <header class="bg-white border-b border-slate-200 px-6 py-3 flex justify-between items-center shadow-sm z-20 shrink-0">
            <div class="flex items-center gap-2">
                <div class="bg-blue-600 text-white p-1.5 rounded-lg shadow-md">
                    <i data-lucide="layers" size="20"></i>
                </div>
                <h1 class="font-bold text-xl tracking-tight text-slate-800">Meta-Analysis Pro <span class="text-xs font-normal text-slate-400 ml-2">v2.2 Safe Edition</span></h1>
            </div>
            <div class="flex items-center gap-4">
                 <span class="text-[10px] uppercase font-bold text-slate-400 tracking-wider">Client-side Calculation</span>
                 <button onclick="loadExampleData()" class="text-xs text-blue-600 font-semibold hover:bg-blue-50 px-3 py-1.5 rounded transition">
                    サンプルデータ読込
                 </button>
            </div>
        </header>
    
        <main class="flex-1 flex overflow-hidden">
            
            <aside class="w-[380px] bg-white border-r border-slate-200 flex flex-col h-full shadow-[4px_0_24px_rgba(0,0,0,0.02)] z-10 shrink-0">
                
                <div class="flex border-b border-slate-200 bg-slate-50/50">
                    <button onclick="switchTab('data')" id="tab-data" class="flex-1 py-3 text-xs uppercase font-bold tracking-wide border-b-2 border-blue-600 text-blue-600 hover:bg-slate-50 transition">
                        Data Input
                    </button>
                    <button onclick="switchTab('settings')" id="tab-settings" class="flex-1 py-3 text-xs uppercase font-bold tracking-wide border-b-2 border-transparent text-slate-500 hover:text-slate-700 hover:bg-slate-50 transition">
                        Analysis & Settings
                    </button>
                </div>
    
                <div id="panel-data" class="panel-container p-5 overflow-y-auto custom-scroll">
                    <div class="text-xs text-slate-500 mb-4 leading-relaxed bg-slate-50 p-4 rounded-lg border border-slate-200">
                        <p class="font-bold text-slate-700 mb-1">CSV/Excel形式データ貼り付け:</p>
                        <div class="grid grid-cols-2 gap-2 mt-2">
                            <div><span class="font-semibold">Events_E</span>: 介入群イベント数</div>
                            <div><span class="font-semibold">Total_E</span>: 介入群総数</div>
                            <div><span class="font-semibold">Events_C</span>: 対照群イベント数</div>
                            <div><span class="font-semibold">Total_C</span>: 対照群総数</div>
                            <div class="col-span-2"><span class="font-semibold">Study</span>: 研究名 / <span class="font-semibold">Subgroup</span>: 分類</div>
                        </div>
                    </div>
                    
                    <div id="parseMessage"></div>
                    
                    <textarea id="inputData" class="flex-1 w-full border border-slate-300 rounded-lg p-3 font-mono text-xs focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none resize-none mb-4 leading-normal shadow-inner bg-slate-50 focus:bg-white transition-colors" 
                        placeholder="ここにデータを貼り付けてください..."></textarea>
                    
                    <button onclick="processData()" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded-lg shadow-lg hover:shadow-xl transition active:scale-[0.98] flex justify-center items-center gap-2">
                        <i data-lucide="play" size="18"></i> 解析実行 (Analyze)
                    </button>
                </div>
    
                <div id="panel-settings" class="hidden panel-container p-5 overflow-y-auto custom-scroll">
                    
                    <div class="bg-white p-4 rounded-xl border border-slate-200 mb-6 space-y-5 shadow-sm ring-1 ring-slate-100">
                        
                        <div>
                            <label class="block text-[10px] uppercase font-bold text-slate-500 mb-2">Effect Measure</label>
                            <div class="flex rounded-lg shadow-sm isolate">
                                <button onclick="setMetric('RR')" id="btn-RR" class="metric-btn flex-1 py-2 text-xs font-bold border rounded-l-md transition z-10 focus:z-20">Risk Ratio</button>
                                <button onclick="setMetric('OR')" id="btn-OR" class="metric-btn flex-1 py-2 text-xs font-bold border-t border-b border-r transition z-10 focus:z-20">Odds Ratio</button>
                                <button onclick="setMetric('RD')" id="btn-RD" class="metric-btn flex-1 py-2 text-xs font-bold border-t border-b border-r rounded-r-md transition z-10 focus:z-20">Risk Diff</button>
                            </div>
                        </div>
    
                        <div>
                            <label class="block text-[10px] uppercase font-bold text-slate-500 mb-2">Pooling Model</label>
                            <div class="relative">
                                <select id="modelSelect" onchange="runAnalysis()" class="w-full text-sm font-medium text-slate-700 border-slate-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500 py-2.5 pl-3 pr-8 bg-slate-50 hover:bg-white transition cursor-pointer appearance-none">
                                    <option value="random">Random Effects (DerSimonian-Laird)</option>
                                    <option value="fixed">Fixed Effect (Inverse Variance)</option>
                                </select>
                                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-slate-500">
                                    <i data-lucide="chevron-down" size="14"></i>
                                </div>
                            </div>
                        </div>
    
                        <div class="pt-2 border-t border-slate-100">
                             <button id="swapBtn" onclick="swapGroups()" class="w-full flex items-center justify-center gap-2 bg-white text-slate-600 border border-slate-300 hover:bg-slate-50 hover:text-slate-800 font-medium py-2.5 px-3 rounded-lg text-xs transition shadow-sm group">
                                 <i data-lucide="arrow-left-right" size="14" class="group-hover:text-blue-600 transition-colors"></i>
                                <span id="swapBtnText">介入群 ⇄ 対照群 を入れ替え</span>
                            </button>
                        </div>
                    </div>
    
                    <div class="flex-1 flex flex-col min-h-0">
                        <div class="flex justify-between items-center mb-3 pb-2 border-b border-slate-200">
                            <label class="text-xs font-bold uppercase text-slate-500 flex items-center gap-2">
                                Sensitivity Analysis
                            </label>
                            <span class="text-[10px] bg-slate-200 text-slate-600 px-2 py-0.5 rounded-full font-mono font-bold" id="studyCountBadge">0</span>
                        </div>
                        
                        <div id="studyTree" class="space-y-3 flex-1 overflow-y-auto pr-2 custom-scroll">
                            <div class="text-center text-slate-400 text-xs mt-10 italic">データを読み込んでください...</div>
                        </div>
                    </div>
                </div>
            </aside>
    
            <section class="flex-1 bg-slate-100/80 overflow-y-auto relative flex flex-col min-w-0">
                
                <div class="flex-1 p-6 flex flex-col min-h-[500px]">
                    <div class="bg-white rounded-xl shadow-md border border-slate-200 flex-1 flex flex-col overflow-hidden relative">
                        <div class="px-5 py-4 border-b border-slate-100 flex justify-between items-center bg-white z-10">
                            <h2 class="font-bold text-slate-800 text-sm flex items-center gap-2">
                                <i data-lucide="bar-chart-2" size="18" class="text-blue-600"></i> Forest Plot
                            </h2>
                            <div class="text-xs text-slate-500 flex gap-4">
                                <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-blue-600"></span> Study</span>
                                <span class="flex items-center gap-1"><span class="w-2 h-2 transform rotate-45 bg-red-600"></span> Pooled Effect</span>
                            </div>
                        </div>
                        
                        <div class="flex-1 relative w-full overflow-hidden bg-white">
                            <div id="forestPlot" class="w-full h-full absolute inset-0"></div>
                        </div>
                    </div>
                </div>
    
                <div class="mx-6 mb-6 bg-white rounded-xl shadow-md border border-slate-200 overflow-hidden shrink-0">
                    <div class="bg-slate-50 px-5 py-3 border-b border-slate-200 flex justify-between items-center">
                        <h2 class="font-bold text-slate-700 text-sm flex items-center gap-2">
                            <i data-lucide="table" size="16" class="text-blue-600"></i> Statistical Details
                        </h2>
                        <button onclick="copyTableToClipboard()" class="text-xs bg-white border border-slate-300 text-slate-600 hover:text-blue-600 hover:border-blue-400 px-3 py-1.5 rounded transition shadow-sm flex items-center gap-1.5 font-medium">
                            <i data-lucide="copy" size="12"></i> Copy Table
                        </button>
                    </div>
                    <div class="overflow-x-auto max-h-[300px] custom-scroll">
                        <table class="w-full text-xs text-left whitespace-nowrap">
                            <thead class="bg-slate-50 text-slate-500 font-semibold border-b border-slate-200 sticky top-0 z-10 shadow-[0_1px_2px_rgba(0,0,0,0.03)]">
                                <tr>
                                    <th class="px-4 py-3 w-1/6">Subgroup</th>
                                    <th class="px-4 py-3 w-1/4">Study</th>
                                    <th class="px-4 py-3 text-right">Events (E)</th>
                                    <th class="px-4 py-3 text-right">Total (E)</th>
                                    <th class="px-4 py-3 text-right">Events (C)</th>
                                    <th class="px-4 py-3 text-right">Total (C)</th>
                                    <th class="px-4 py-3 text-right">Weight</th>
                                    <th class="px-4 py-3 text-right">Effect [95% CI]</th>
                                </tr>
                            </thead>
                            <tbody id="statsTableBody" class="divide-y divide-slate-100 text-slate-700"></tbody>
                        </table>
                    </div>
                </div>
            </section>
        </main>
    
    <script>
        /**
         * META-ANALYSIS ENGINE v2.2 (Safe Edition)
         * Includes error guards for render functions to prevent crashes on undefined values.
         */
    
        // --- State ---
        const APP_STATE = {
            rawData: [],            
            processedData: [],      
            groupedData: {},        
            excludedStudyIds: new Set(),
            metric: 'RR',           
            model: 'random',        
            isSwapped: false,
            lastResults: null
        };
    
        // --- Config ---
        const CONFIG = {
            colors: {
                studyBox: '#2563eb',   // Blue 600
                studyLine: '#334155',  // Slate 700 (Darker for visibility)
                diamondSub: '#059669', // Emerald 600
                diamondTotal: '#dc2626', // Red 600
                nullLine: '#0f172a',    // Slate 900
                grid: '#e2e8f0'         // Slate 200
            },
            layout: {
                rowHeight: 36, // Slightly taller rows for better separation
                markerMin: 6,
                markerMax: 14
            }
        };
    
        // --- Initialization ---
        document.addEventListener('DOMContentLoaded', () => {
            lucide.createIcons();
            updateMetricUI();
            loadExampleData();
            window.addEventListener('resize', () => {
                 if(APP_STATE.lastResults) renderPlot(APP_STATE.lastResults);
            });
        });
    
        const SAMPLE_DATA = `Study,Events_E,Total_E,Events_C,Total_C,Subgroup
    Smith 2010,15,100,20,100,Age < 65
    Jones 2011,10,120,15,110,Age < 65
    Brown 2012,25,150,30,150,Age < 65
    Williams 2013,40,200,35,200,Age >= 65
    Taylor 2014,5,50,10,50,Age >= 65
    Davis 2015,12,80,18,80,Age >= 65
    Miller 2016,0,40,2,40,Comorbidity
    Wilson 2017,8,60,5,60,Comorbidity`;
    
        function loadExampleData() {
            document.getElementById('inputData').value = SAMPLE_DATA;
            showMessage('success', 'サンプルデータをセットしました。「解析実行」を押してください。');
        }
    
        // --- Data Processing ---
        function processData() {
            const inputStr = document.getElementById('inputData').value.trim();
            if (!inputStr) return showMessage('error', 'データが空です。');
    
            const result = Papa.parse(inputStr, { header: true, skipEmptyLines: 'greedy' });
            
            if (result.errors.length > 0 && !result.data.length) {
                return showMessage('error', 'CSV解析エラー。');
            }
    
            const normalized = [];
            let validCount = 0;
    
            result.data.forEach(row => {
                const getCol = (patterns) => {
                    const key = Object.keys(row).find(k => patterns.some(p => k.toLowerCase().trim().includes(p)));
                    return key ? row[key] : null;
                };
    
                const study = getCol(['study', 'name', 'author']);
                const ee = getCol(['events_e', 'eventse', 'e_events']);
                const te = getCol(['total_e', 'totale', 'n_e']);
                const ec = getCol(['events_c', 'eventsc', 'c_events']);
                const tc = getCol(['total_c', 'totalc', 'n_c']);
                const sub = getCol(['subgroup', 'group']) || 'Overall';
    
                if (study && ee != null && te != null && ec != null && tc != null) {
                    const n_ee = parseFloat(String(ee).replace(/,/g,''));
                    const n_te = parseFloat(String(te).replace(/,/g,''));
                    const n_ec = parseFloat(String(ec).replace(/,/g,''));
                    const n_tc = parseFloat(String(tc).replace(/,/g,''));
    
                    if (!isNaN(n_ee) && !isNaN(n_te) && !isNaN(n_ec) && !isNaN(n_tc) && n_te > 0 && n_tc > 0) {
                         normalized.push({
                            Study: study.trim(),
                            Events_E: n_ee, Total_E: n_te,
                            Events_C: n_ec, Total_C: n_tc,
                            Subgroup: sub.trim()
                        });
                        validCount++;
                    }
                }
            });
    
            if (validCount === 0) return showMessage('error', '有効なデータが見つかりません。列名を確認してください。');
    
            APP_STATE.rawData = normalized;
            APP_STATE.excludedStudyIds.clear();
            APP_STATE.isSwapped = false;
            
            showMessage('success', `${validCount}件の研究を読み込みました。`);
            updateSwapUI();
            applyTransformAndAnalyze();
            switchTab('settings');
        }
    
        // --- Logic Control ---
        function swapGroups() {
            APP_STATE.isSwapped = !APP_STATE.isSwapped;
            updateSwapUI();
            applyTransformAndAnalyze();
        }
    
        function updateSwapUI() {
            const btn = document.getElementById('swapBtn');
            const txt = document.getElementById('swapBtnText');
            if (APP_STATE.isSwapped) {
                btn.classList.add('bg-amber-50', 'border-amber-300', 'text-amber-800');
                btn.classList.remove('bg-white', 'text-slate-600');
                txt.innerText = "入れ替え中 (介入 ⇄ 対照)";
            } else {
                btn.classList.remove('bg-amber-50', 'border-amber-300', 'text-amber-800');
                btn.classList.add('bg-white', 'text-slate-600');
                txt.innerText = "介入群 ⇄ 対照群 を入れ替え";
            }
        }
    
        function applyTransformAndAnalyze() {
            APP_STATE.processedData = APP_STATE.rawData.map(row => {
                if (APP_STATE.isSwapped) {
                    return { ...row, Events_E: row.Events_C, Total_E: row.Total_C, Events_C: row.Events_E, Total_C: row.Total_E };
                }
                return { ...row };
            });
    
            APP_STATE.groupedData = {};
            APP_STATE.processedData.forEach(row => {
                if (!APP_STATE.groupedData[row.Subgroup]) APP_STATE.groupedData[row.Subgroup] = [];
                APP_STATE.groupedData[row.Subgroup].push(row);
            });
    
            updateTreeUI();
            runAnalysis();
        }
    
        function setMetric(m) {
            APP_STATE.metric = m;
            updateMetricUI();
            if (APP_STATE.rawData.length) runAnalysis();
        }
    
        function updateMetricUI() {
            ['RR', 'OR', 'RD'].forEach(m => {
                const btn = document.getElementById(`btn-${m}`);
                const isActive = m === APP_STATE.metric;
                btn.className = `metric-btn flex-1 py-2 text-xs font-bold transition z-10 focus:z-20 ${isActive ? 'bg-blue-600 text-white border-blue-600 shadow-md' : 'bg-white text-slate-700 border-slate-300 hover:bg-slate-50'}`;
                if(m === 'RR') btn.classList.add('rounded-l-md');
                else if(m === 'RD') btn.classList.add('rounded-r-md');
                else btn.classList.add('border-t', 'border-b', 'border-r');
            });
        }
    
        // --- Statistics ---
        function calculateStudyStats(e1, n1, e2, n2, metric) {
            const hasZero = (e1 === 0 || e2 === 0 || (n1 - e1) === 0 || (n2 - e2) === 0);
            let a = e1, b = n1 - e1, c = e2, d = n2 - e2;
            let N1 = n1, N2 = n2;
    
            if (hasZero && metric !== 'RD') {
                a += 0.5; b += 0.5; c += 0.5; d += 0.5;
                N1 += 1.0; N2 += 1.0;
            }
    
            let est, se;
            try {
                if (metric === 'RR') {
                    est = Math.log((a / N1) / (c / N2));
                    se = Math.sqrt((1/a) - (1/N1) + (1/c) - (1/N2));
                } else if (metric === 'OR') {
                    est = Math.log((a * d) / (b * c));
                    se = Math.sqrt((1/a) + (1/b) + (1/c) + (1/d));
                } else {
                    const p1 = e1/n1, p2 = e2/n2;
                    est = p1 - p2;
                    se = Math.sqrt((p1*(1-p1)/n1) + (p2*(1-p2)/n2));
                    if (se === 0 && hasZero) se = Math.sqrt(((a/N1)*(1-a/N1)/N1) + ((c/N2)*(1-c/N2)/N2));
                }
            } catch(e) { return null; }
    
            if (!isFinite(est) || !isFinite(se) || isNaN(est) || isNaN(se) || se <= 0) return null;
    
            return { est, se, weight_iv: 1 / (se * se) };
        }
    
        function runAnalysis() {
            APP_STATE.model = document.getElementById('modelSelect').value;
            const results = { subgroups: [], overall: null };
            const groups = Object.keys(APP_STATE.groupedData).sort();
            let allValidStudies = [];
    
            groups.forEach(gName => {
                const rawStudies = APP_STATE.groupedData[gName].filter(s => !APP_STATE.excludedStudyIds.has(s.Study));
                if (!rawStudies.length) return;
    
                const studies = rawStudies.map(s => {
                    const stats = calculateStudyStats(s.Events_E, s.Total_E, s.Events_C, s.Total_C, APP_STATE.metric);
                    if (!stats) return null;
                    return { original: s, ...stats };
                }).filter(s => s !== null);
    
                if (!studies.length) return;
    
                let sumWi = 0, sumWiYi = 0, sumWi2 = 0;
                studies.forEach(s => {
                    sumWi += s.weight_iv;
                    sumWiYi += s.weight_iv * s.est;
                    sumWi2 += s.weight_iv ** 2;
                });
                const fixedEst = sumWiYi / sumWi;
                
                let Q = 0;
                studies.forEach(s => Q += s.weight_iv * ((s.est - fixedEst) ** 2));
                const df = studies.length - 1;
                const I2 = df > 0 ? Math.max(0, ((Q - df) / Q) * 100) : 0;
                
                let tau2 = 0;
                if (Q > df) {
                    const denom = sumWi - (sumWi2 / sumWi);
                    if (denom > 0) tau2 = (Q - df) / denom;
                }
    
                let pooledEst, pooledSE, totalWeight = 0;
                studies.forEach(s => {
                    s.finalWeight = (APP_STATE.model === 'random') ? (1 / (s.se**2 + tau2)) : s.weight_iv;
                    totalWeight += s.finalWeight;
                });
    
                let sumWy = 0;
                studies.forEach(s => {
                    s.relWeight = (s.finalWeight / totalWeight) * 100;
                    sumWy += s.finalWeight * s.est;
                    s.lower = s.est - 1.96 * s.se;
                    s.upper = s.est + 1.96 * s.se;
                });
    
                pooledEst = sumWy / totalWeight;
                pooledSE = 1 / Math.sqrt(totalWeight);
    
                results.subgroups.push({
                    name: gName,
                    studies: studies,
                    meta: {
                        est: pooledEst,
                        lower: pooledEst - 1.96 * pooledSE,
                        upper: pooledEst + 1.96 * pooledSE,
                        i2: I2, tau2, Q
                    }
                });
                allValidStudies = [...allValidStudies, ...studies];
            });
    
            if (allValidStudies.length > 0) {
                let sumWi = 0, sumWiYi = 0, sumWi2 = 0;
                allValidStudies.forEach(s => {
                    sumWi += s.weight_iv;
                    sumWiYi += s.weight_iv * s.est;
                    sumWi2 += s.weight_iv ** 2;
                });
                const fixedGlobal = sumWiYi / sumWi;
                let Q_glob = 0;
                allValidStudies.forEach(s => Q_glob += s.weight_iv * ((s.est - fixedGlobal)**2));
                const df_glob = allValidStudies.length - 1;
                let tau2_glob = 0;
                 if (Q_glob > df_glob) {
                    const denom = sumWi - (sumWi2 / sumWi);
                    if (denom > 0) tau2_glob = (Q_glob - df_glob) / denom;
                }
                
                let globWeight = 0, globWy = 0;
                allValidStudies.forEach(s => {
                    const w = (APP_STATE.model === 'random') ? (1 / (s.se**2 + tau2_glob)) : s.weight_iv;
                    globWeight += w;
                    globWy += w * s.est;
                });
                
                const ovEst = globWy / globWeight;
                const ovSE = 1 / Math.sqrt(globWeight);
    
                results.overall = {
                    est: ovEst,
                    lower: ovEst - 1.96 * ovSE,
                    upper: ovEst + 1.96 * ovSE,
                    i2: df_glob > 0 ? Math.max(0, ((Q_glob - df_glob) / Q_glob) * 100) : 0,
                    tau2: tau2_glob
                };
            }
    
            APP_STATE.lastResults = results;
            renderPlot(results);
            renderTable(results);
        }
    
        // --- Visualization: The Spacer Logic ---
        function renderPlot(results) {
            if (!results.overall) {
                document.getElementById('forestPlot').innerHTML = '<div class="flex items-center justify-center h-full text-slate-400">データがありません</div>';
                return;
            }
    
            const isLog = APP_STATE.metric !== 'RD';
            const rows = []; 
    
            results.subgroups.forEach(g => {
                rows.push({ type: 'header', text: g.name });
                g.studies.forEach(s => rows.push({ type: 'study', data: s }));
                rows.push({ type: 'subtotal', data: g.meta, text: `Subtotal (${g.name})` });
                rows.push({ type: 'spacer' });
            });
            if(rows[rows.length-1].type === 'spacer') rows.pop();
            
            rows.push({ type: 'spacer' });
            rows.push({ type: 'total', data: results.overall, text: 'Overall Total' });
    
            const plotHeight = Math.max(450, rows.length * CONFIG.layout.rowHeight + 120);
    
            // Smart Scaling with safety check
            let validLows = [], validHighs = [];
            const pushLims = (l, u) => { if(isFinite(l) && isFinite(u)) { validLows.push(l); validHighs.push(u); }};
    
            pushLims(results.overall.lower, results.overall.upper);
            results.subgroups.forEach(g => g.studies.forEach(s => {
                if (s.relWeight > 1.0) pushLims(s.lower, s.upper);
            }));
    
            let minX = Math.min(...validLows);
            let maxX = Math.max(...validHighs);
            const rangeSpan = maxX - minX;
            minX -= rangeSpan * 0.15; // slightly more padding for lines
            maxX += rangeSpan * 0.15;
    
            const traceData = {
                x: [], y: [], 
                error_x: { type: 'data', array: [], arrayminus: [], color: CONFIG.colors.studyLine, thickness: 1.5, visible: true },
                text: [], 
                marker: { size: [], color: CONFIG.colors.studyBox, symbol: 'square' },
                type: 'scatter', mode: 'markers', hoverinfo: 'text'
            };
    
            const shapes = [];
            const annotations = [];
            const getY = (i) => rows.length - 1 - i;
    
            // Header for columns
            const headerY = rows.length; 
            // We add "Static Headers" as annotations outside the loop
            annotations.push(
                { x: -0.04, xref: 'paper', y: headerY, yref: 'y', text: "<b>Study</b>", xanchor: 'right', showarrow: false, font: {size: 13} },
                { x: 1.04, xref: 'paper', y: headerY, yref: 'y', text: `<b>${APP_STATE.metric} [95% CI]</b>`, xanchor: 'left', showarrow: false, font: {size: 13} }
            );
    
            rows.forEach((row, i) => {
                const yPos = getY(i);
                
                if (row.type === 'study') {
                    const s = row.data;
                    // Safety: Ensure values are numbers before Math.exp/toFixed
                    const rawEst = s.est ?? 0;
                    const rawLow = s.lower ?? 0;
                    const rawHigh = s.upper ?? 0;
    
                    const val = isLog ? Math.exp(rawEst) : rawEst;
                    const low = isLog ? Math.exp(rawLow) : rawLow;
                    const high = isLog ? Math.exp(rawHigh) : rawHigh;
                    const mSize = Math.min(CONFIG.layout.markerMax, Math.max(CONFIG.layout.markerMin, Math.sqrt(s.relWeight || 0)*2.5));
    
                    traceData.x.push(val);
                    traceData.y.push(yPos);
                    traceData.marker.size.push(mSize);
                    
                    const safeHigh = Math.min(high, isLog ? Math.exp(maxX * 2) : maxX * 2); 
                    const safeLow = Math.max(low, isLog ? Math.exp(minX - 1) : minX - 1);
                    traceData.error_x.array.push(safeHigh - val);
                    traceData.error_x.arrayminus.push(val - safeLow);
    
                    const ciTxt = `[${low.toFixed(2)}, ${high.toFixed(2)}]`;
                    traceData.text.push(`<b>${s.original.Study}</b><br>${APP_STATE.metric}: ${val.toFixed(2)} ${ciTxt}<br>Wt: ${(s.relWeight||0).toFixed(1)}%`);
    
                    // Left Text
                    annotations.push({ 
                        x: -0.04, xref: 'paper', 
                        y: yPos, text: s.original.Study, 
                        xanchor: 'right', showarrow: false, font: {size: 11} 
                    });
    
                    // Right Text
                    annotations.push({ 
                        x: 1.04, xref: 'paper', 
                        y: yPos, text: `${val.toFixed(2)} <span class="text-slate-400 text-[10px]">${ciTxt}</span>`, 
                        xanchor: 'left', showarrow: false, font: {size: 11, family: 'monospace'} 
                    });
                } 
                else if (row.type === 'header') {
                    annotations.push({ x: -0.04, xref: 'paper', y: yPos, text: `<b>${row.text}</b>`, xanchor: 'right', showarrow: false, font: {size: 12} });
                }
                else if (row.type === 'subtotal' || row.type === 'total') {
                    const d = row.data;
                    const rawEst = d.est ?? 0;
                    const rawLow = d.lower ?? 0;
                    const rawHigh = d.upper ?? 0;
    
                    const val = isLog ? Math.exp(rawEst) : rawEst;
                    const low = isLog ? Math.exp(rawLow) : rawLow;
                    const high = isLog ? Math.exp(rawHigh) : rawHigh;
                    const color = row.type === 'total' ? CONFIG.colors.diamondTotal : CONFIG.colors.diamondSub;
    
                    const halfH = 0.35; 
                    shapes.push({
                        type: 'path',
                        path: `M ${low} ${yPos} L ${val} ${yPos+halfH} L ${high} ${yPos} L ${val} ${yPos-halfH} Z`,
                        fillcolor: color, line: {width: 0}, xref: 'x', yref: 'y'
                    });
    
                    annotations.push(
                        { x: -0.04, xref: 'paper', y: yPos, text: `<b>${row.text}</b>`, xanchor: 'right', showarrow: false, font: {size: 12, color: color} },
                        { x: 1.04, xref: 'paper', y: yPos, text: `<b>${val.toFixed(2)}</b> <span class="text-[10px]">I²=${(d.i2||0).toFixed(0)}%</span>`, xanchor: 'left', showarrow: false, font: {size: 12, color: color} }
                    );
                }
            });
    
            const rangePad = isLog ? 1.5 : (maxX - minX)*0.2;
            const axisRange = isLog 
                ? [Math.log10(Math.max(0.01, Math.exp(minX))), Math.log10(Math.min(1000, Math.exp(maxX)))] 
                : [minX - rangePad, maxX + rangePad];
    
            const layout = {
                height: plotHeight,
                // Margins for external text
                margin: { l: 280, r: 240, t: 60, b: 60 },
                xaxis: {
                    type: isLog ? 'log' : 'linear',
                    range: isLog ? undefined : axisRange,
                    title: { text: `${APP_STATE.metric} (95% CI)`, font: {size: 12} },
                    zeroline: false,
                    gridcolor: CONFIG.colors.grid,
                    gridwidth: 1
                },
                yaxis: {
                    showticklabels: false,
                    range: [-1, rows.length + 1],
                    zeroline: false,
                    gridcolor: 'transparent'
                },
                shapes: [
                    { 
                        type: 'line',
                        x0: isLog ? 1 : 0, x1: isLog ? 1 : 0,
                        y0: 0, y1: 1, yref: 'paper',
                        line: { color: CONFIG.colors.nullLine, width: 1.5 }
                    },
                    ...shapes
                ],
                annotations: annotations,
                showlegend: false,
                hovermode: 'closest',
                paper_bgcolor: 'white',
                plot_bgcolor: 'white'
            };
    
            Plotly.newPlot('forestPlot', [traceData], layout, { displayModeBar: true, responsive: true });
        }
    
        // --- Table & Utils (FIXED FOR SAFETY) ---
        function renderTable(results) {
            const tbody = document.getElementById('statsTableBody');
            tbody.innerHTML = '';
            if (!results.overall) return;
            const isLog = APP_STATE.metric !== 'RD';
            
            // --- SAFE FORMATTER FIX ---
            // Prevents crash when value is undefined/null
            const fmt = (v) => {
                if (v === undefined || v === null || isNaN(v)) return "-";
                const val = isLog ? Math.exp(v) : v;
                return val.toFixed(2);
            };
    
            results.subgroups.forEach(g => {
                tbody.innerHTML += `<tr class="bg-slate-50 font-bold text-slate-800"><td colspan="8" class="px-4 py-2">${g.name}</td></tr>`;
                g.studies.forEach(s => {
                    tbody.innerHTML += `
                        <tr class="hover:bg-blue-50 transition border-b border-slate-50 text-[11px]">
                            <td class="px-4 py-1"></td>
                            <td class="px-4 py-1 font-medium text-slate-700 truncate max-w-[150px]">${s.original.Study}</td>
                            <td class="px-4 py-1 text-right text-slate-500">${s.original.Events_E}</td>
                            <td class="px-4 py-1 text-right text-slate-400">${s.original.Total_E}</td>
                            <td class="px-4 py-1 text-right text-slate-500">${s.original.Events_C}</td>
                            <td class="px-4 py-1 text-right text-slate-400">${s.original.Total_C}</td>
                            <td class="px-4 py-1 text-right">${(s.relWeight||0).toFixed(1)}%</td>
                            <td class="px-4 py-1 text-right font-mono text-blue-700">${fmt(s.est)} [${fmt(s.lower)}, ${fmt(s.upper)}]</td>
                        </tr>`;
                });
                tbody.innerHTML += `
                    <tr class="bg-blue-50/50 font-semibold border-b border-blue-100 text-xs">
                        <td colspan="6" class="px-4 py-2 text-right text-blue-800">Subtotal (${g.name}) <span class="text-[10px] font-normal text-slate-500 ml-2">I²=${(g.meta.i2||0).toFixed(0)}%</span></td>
                        <td class="px-4 py-2 text-right text-blue-800">-</td>
                        <td class="px-4 py-2 text-right font-mono text-blue-800">${fmt(g.meta.est)} [${fmt(g.meta.lower)}, ${fmt(g.meta.upper)}]</td>
                    </tr>`;
            });
    
            if (results.overall) {
                 tbody.innerHTML += `
                    <tr class="bg-red-50 font-bold border-t-2 border-red-100 text-xs">
                        <td colspan="6" class="px-4 py-3 text-right text-red-800">Overall <span class="text-[10px] font-normal text-slate-500 ml-2">I²=${(results.overall.i2||0).toFixed(0)}%, τ²=${(results.overall.tau2||0).toFixed(3)}</span></td>
                        <td class="px-4 py-3 text-right text-red-800">100%</td>
                        <td class="px-4 py-3 text-right font-mono text-red-800 text-sm">${fmt(results.overall.est)} [${fmt(results.overall.lower)}, ${fmt(results.overall.upper)}]</td>
                    </tr>`;
            }
        }
    
        function showMessage(type, text) {
            const d = document.getElementById('parseMessage');
            const color = type === 'error' ? 'error-msg' : 'success-msg';
            d.innerHTML = `<div class="msg-box ${color}"><i data-lucide="${type==='error'?'alert-circle':'check-circle'}" size="16"></i> ${text}</div>`;
            lucide.createIcons();
            if(type === 'success') setTimeout(() => d.innerHTML = '', 4000);
        }
    
        function switchTab(t) {
            document.getElementById('panel-data').classList.toggle('hidden', t !== 'data');
            document.getElementById('panel-settings').classList.toggle('hidden', t !== 'settings');
            const t1 = document.getElementById('tab-data');
            const t2 = document.getElementById('tab-settings');
            const activeClass = ['border-blue-600', 'text-blue-600'];
            const inactiveClass = ['border-transparent', 'text-slate-500'];
            if (t === 'data') {
                t1.classList.add(...activeClass); t1.classList.remove(...inactiveClass);
                t2.classList.add(...inactiveClass); t2.classList.remove(...activeClass);
            } else {
                t2.classList.add(...activeClass); t2.classList.remove(...inactiveClass);
                t1.classList.add(...inactiveClass); t1.classList.remove(...activeClass);
            }
        }
    
        function updateTreeUI() {
            const c = document.getElementById('studyTree');
            c.innerHTML = '';
            Object.keys(APP_STATE.groupedData).sort().forEach(g => {
                const studies = APP_STATE.groupedData[g];
                const gDiv = document.createElement('div');
                gDiv.className = 'border border-slate-200 rounded-lg bg-white overflow-hidden';
                const allChecked = studies.every(s => !APP_STATE.excludedStudyIds.has(s.Study));
                gDiv.innerHTML = `
                    <div class="bg-slate-50 p-2.5 flex items-center gap-2 border-b border-slate-100">
                        <input type="checkbox" class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500" ${allChecked ? 'checked' : ''} onchange="toggleGroup('${g}', this.checked)">
                        <span class="text-xs font-bold text-slate-700">${g} (${studies.length})</span>
                    </div>`;
                const list = document.createElement('div');
                list.className = 'p-1';
                studies.forEach(s => {
                    const checked = !APP_STATE.excludedStudyIds.has(s.Study);
                    const row = document.createElement('label');
                    row.className = 'flex items-center gap-2 p-1.5 hover:bg-slate-50 rounded cursor-pointer';
                    row.innerHTML = `
                        <input type="checkbox" class="w-3.5 h-3.5 rounded text-blue-600 focus:ring-blue-500 border-slate-300" ${checked ? 'checked' : ''} onchange="toggleStudy('${s.Study}', this.checked)">
                        <span class="text-xs text-slate-600 truncate">${s.Study}</span>`;
                    list.appendChild(row);
                });
                gDiv.appendChild(list);
                c.appendChild(gDiv);
            });
            document.getElementById('studyCountBadge').innerText = Object.values(APP_STATE.groupedData).flat().length;
        }
    
        window.toggleStudy = (id, checked) => {
            if(checked) APP_STATE.excludedStudyIds.delete(id);
            else APP_STATE.excludedStudyIds.add(id);
            updateTreeUI();
            runAnalysis();
        };
    
        window.toggleGroup = (g, checked) => {
            APP_STATE.groupedData[g].forEach(s => {
                if(checked) APP_STATE.excludedStudyIds.delete(s.Study);
                else APP_STATE.excludedStudyIds.add(s.Study);
            });
            updateTreeUI();
            runAnalysis();
        };
    
        function copyTableToClipboard() {
            const rows = Array.from(document.querySelectorAll('#statsTableBody tr'));
            const txt = rows.map(r => Array.from(r.querySelectorAll('td')).map(c => c.innerText.replace(/\s+/g,' ').trim()).join('\t')).join('\n');
            navigator.clipboard.writeText("Subgroup\tStudy\tEventsE\tTotalE\tEventsC\tTotalC\tWt\tEffect\n" + txt).then(() => alert('クリップボードにコピーしました'));
        }
    </script>
    </body>
    </html>

    作成方法2:デフォルト ツールをCanvasにする

    画像

    データはどうするの?

    例えばエクセルで、こんな表を作ったりします。

    画像

    これを、コピーして、Gemにテキストで貼り付けて、送信することで作成始めたが、最終的には、Gemを空白のまま送信してから、後から、データ入力に入れて動かす事に変更しています。
    Gemでなく、普通にCanvas選択してコード入力でもアプリは立ち上がる。
    介入と対照は、間違っていても後から入れ替えできます(こだわりました)。

    注意:Study,Events_E,Total_E,Events_C,Total_C,Subgroupの項目です。Subgroupは、なくてもよいです。一応、ルールは以下だが、若干違うこともあるので、いろいろ試して。

    # 標準形式 Study,Events_E,Total_E,Events_C,Total_C,Subgroup
    # 順序が違う形式 Subgroup,Study,Total_E,Events_E,Total_C,Events_C
    # 別名を使った形式Author,Exp_Events,N_Treatment,Control_Events,N_Control,Group
    # 短縮形式 Study,EE,TE,EC,TC,Subgroup
    カンマ区切り、タブ区切り、スペース区切りでも可だが、どうもカンマ区切りのみのようだ?

    論文のフォレストプロットの数字をどのように取り出すのか?

    フレストプロットをまず画面キャプチャーか何かで図として保存してください。
    次にその図をジェミニなどに添付して取り込んでください。
    以下のプロンプトなどで論文名と数字を取り出してください。
    サブグループ解析などの場合、同じ論文の名前が入っています。これは必ず論文1,2という感じで、名前を違うのにしてください。

    ここから、論文名、イベント数, 症例数, サブグループの名前を抜き出して一覧にしてください。すべての数字をセルごとに分けてください。

    動画のデータは?

    Study,Total_E,Events_E,Total_C,Events_C,Subgroup
    Elhennawy2021,31,1,32,2,Primary
    Orhan2010,31,2,32,4,Primary
    Labib2019,54,7,52,10,Permanent
    Maltz2018,115,19,114,39,Permanent
    Orhan2010_2,19,1,17,1,Permanent

    Study,Events_E,Total_E,Events_C,Total_C,Subgroup
    Smith 2010,15,100,20,100,Age < 65
    Jones 2011,10,120,15,110,Age < 65
    Brown 2012,25,150,30,150,Age < 65
    Williams 2013,40,200,35,200,Age >= 65
    Taylor 2014,5,50,10,50,Age >= 65
    Davis 2015,12,80,18,80,Age >= 65
    Miller 2016,0,40,2,40,Comorbidity
    Wilson 2017,8,60,5,60,Comorbidity

    無料だが、マネしてアプリを作ってみたいのですが?

    Geminiの無料の高速モードで、ToolをGanvasにして、

    「2値のメタ分析のアプリを作って」

    と入れて作ったものを見て修正(アプリにならずコードのみなら、アプリとして表示してと一度入れる)

    「データは直接CSVで入力できるように
    フォレストプロットが描写されないので直して」

    と入力だけで、それらしいのが作れます。

    この遊びに没頭して、私みたいに、無駄な時間を使わないように注意しましょうね。

    画像


    例えば、以下の動画など役立ちますが、他にもどんどん新しい解説がでています。


    導入動画は?


    連続量のソフトは?


    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>連続変数メタ分析ツール (Web版 v3.2 - 安定版)</title>
        <!-- Plotlyのみ外部読み込み -->
        <script src="https://cdn.plot.ly/plotly-2.24.1.min.js"></script>
        <style>
            body { font-family: "Helvetica Neue", Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f4f9; color: #333; }
            .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
            h1 { color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 10px; }
            h2 { color: #34495e; margin-top: 30px; font-size: 1.2em; border-left: 5px solid #ff4b4b; padding-left: 10px; }
            
            /* Control Panel Styles */
            .control-panel { display: flex; gap: 20px; background: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; flex-wrap: wrap;}
            .input-group { flex: 1; min-width: 200px; }
            label { display: block; font-weight: bold; margin-bottom: 5px; font-size: 0.9em;}
            
            textarea { width: 100%; height: 150px; font-family: monospace; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
            
            /* Checkbox Style */
            .checkbox-container {
                display: flex;
                align-items: center;
                background: #fff;
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                margin-top: 5px;
                cursor: pointer;
            }
            .checkbox-container input { margin-right: 10px; transform: scale(1.2); cursor: pointer; }
            .checkbox-container:hover { background: #f0f0f0; }
    
            button { background-color: #ff4b4b; color: white; border: none; padding: 12px 25px; font-size: 16px; border-radius: 4px; cursor: pointer; transition: background 0.3s; font-weight: bold; }
            button:hover { background-color: #e04343; }
            
            .results-box { display: flex; gap: 20px; margin-bottom: 20px; }
            .metric { background: #e8f4f8; padding: 15px; border-radius: 5px; flex: 1; text-align: center; }
            .metric h3 { margin: 0 0 10px 0; font-size: 1em; color: #555; }
            .metric .value { font-size: 1.5em; font-weight: bold; color: #007bff; }
            
            #plot-area { width: 100%; height: 600px; }
            select { padding: 8px; width: 100%; border-radius: 4px; border: 1px solid #ccc; }
            .note { font-size: 0.85em; color: #666; margin-top: 5px; }
    
            /* Sensitivity Analysis Specific Styles */
            .sensitivity-panel {
                background: #fff3f3;
                border: 1px solid #ffcccc;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
            }
            .study-list {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-top: 10px;
            }
            .study-toggle {
                display: flex;
                align-items: center;
                background: white;
                border: 1px solid #ccc;
                padding: 5px 10px;
                border-radius: 20px;
                font-size: 0.9em;
                cursor: pointer;
                user-select: none;
                transition: all 0.2s;
            }
            .study-toggle:hover { border-color: #888; }
            .study-toggle.excluded { opacity: 0.6; background: #eee; text-decoration: line-through; color: #888; }
            .study-toggle input { margin-right: 8px; cursor: pointer; }
    
        </style>
    </head>
    <body>
    
    <div class="container">
        <h1>📊 連続変数のメタ分析ツール (Web版)</h1>
        <p>Excelファイル不要。テキストを直接貼り付けて、ブラウザだけで解析できます。</p>
    
        <div class="control-panel">
            <div class="input-group">
                <label>① 効果量の指標</label>
                <select id="measureType">
                    <option value="MD">MD (平均差: Mean Difference)</option>
                    <option value="SMD">SMD (標準化平均差: Hedges' g)</option>
                </select>
            </div>
            <div class="input-group">
                <label>② 統合モデル</label>
                <select id="modelType" onchange="if(globalStudies.length > 0) recalculateAndRender();">
                    <option value="random">ランダム効果モデル (DL法)</option>
                    <option value="fixed">固定効果モデル (IV法)</option>
                </select>
            </div>
            <div class="input-group">
                <label>③ オプション</label>
                <label class="checkbox-container">
                    <input type="checkbox" id="swapGroups" onchange="if(globalStudies.length > 0) recalculateAndRender();">
                    <span style="font-weight: normal;">介入群と対照群を入れ替える</span>
                </label>
            </div>
        </div>
    
        <div class="input-group">
            <label>データ入力 (カンマ区切り: 研究名, N_介入, Mean_介入, SD_介入, N_対照, Mean_対照, SD_対照)</label>
            <textarea id="dataInput">
    Study A, 30, 10.5, 2.1, 30, 8.5, 2.0
    Study B, 105, 12.0, 3.5, 102, 11.0, 3.2
    Study C, 50, 9.8, 2.8, 50, 10.0, 3.0
    Study D, 80, 11.5, 3.0, 82, 10.5, 3.1
    Study E, 45, 10.2, 2.5, 44, 9.5, 2.4</textarea>
            <div class="note">※ 1行目のデータから読み込まれます(ヘッダー行は自動で無視またはスキップされます)。</div>
        </div>
        <br>
        <button onclick="initializeAnalysis()">分析実行</button>
    
        <hr>
    
        <div id="resultsSection" style="display:none;">
            
            <!-- 感度分析エリア -->
            <h2>2. 感度分析:研究の選択</h2>
            <div class="sensitivity-panel">
                <div style="font-size:0.9em; margin-bottom:5px;">以下のチェックボックスを切り替えると、特定研究を除外した場合の結果を即座に確認できます。</div>
                <div id="studyTogglesArea" class="study-list"></div>
            </div>
    
            <h2>3. 分析結果</h2>
            <div class="results-box">
                <div class="metric">
                    <h3>統合推定値 (Pooled Effect)</h3>
                    <div class="value" id="pooledEffect">-</div>
                    <div id="pooledCI" style="margin-top:5px;">95% CI: [- , -]</div>
                    <div id="pValue">p = -</div>
                </div>
                <div class="metric">
                    <h3>異質性 (Heterogeneity)</h3>
                    <div class="value" id="i2Value">-</div>
                    <div id="qValue">Q = -</div>
                </div>
            </div>
    
            <div id="plot-area"></div>
        </div>
    </div>
    
    <script>
        // 統計ライブラリへの依存を排除するためのヘルパー関数
        const Stats = {
            // 標準正規分布の累積分布関数 (CDF) の近似 (Abramowitz and Stegun)
            normalCdf: function(x) {
                var t = 1 / (1 + 0.2316419 * Math.abs(x));
                var d = 0.3989423 * Math.exp(-x * x / 2);
                var prob = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));
                if (x > 0) prob = 1 - prob;
                return prob;
            },
            // 両側p値を計算
            calcTwoSidedP: function(z) {
                return 2 * (1 - this.normalCdf(Math.abs(z)));
            }
        };
    
        let globalStudies = [];
        let excludedIndices = new Set(); 
    
        function initializeAnalysis() {
            const input = document.getElementById('dataInput').value.trim();
            
            const lines = input.split('\n');
            const parsedStudies = [];
            
            try {
                lines.forEach((line, index) => {
                    const trimmedLine = line.trim();
                    if (!trimmedLine) return;
                    
                    const parts = trimmedLine.split(',');
                    if (isNaN(parseFloat(parts[1]))) return; 
    
                    if (parts.length < 7) throw new Error("列数が足りない行があります: " + trimmedLine);
                    
                    parsedStudies.push({
                        originalIndex: index,
                        name: parts[0].trim(),
                        n1: parseFloat(parts[1]),
                        m1: parseFloat(parts[2]),
                        s1: parseFloat(parts[3]),
                        n2: parseFloat(parts[4]),
                        m2: parseFloat(parts[5]),
                        s2: parseFloat(parts[6])
                    });
                });
            } catch (e) {
                alert("データ読み込みエラー: " + e.message);
                return;
            }
    
            if (parsedStudies.length === 0) {
                alert("有効なデータが見つかりませんでした。");
                return;
            }
    
            globalStudies = parsedStudies;
            excludedIndices.clear(); 
    
            renderStudyToggles();
    
            document.getElementById('resultsSection').style.display = 'block';
            recalculateAndRender();
        }
    
        function renderStudyToggles() {
            const container = document.getElementById('studyTogglesArea');
            container.innerHTML = '';
    
            globalStudies.forEach((study, idx) => {
                const label = document.createElement('label');
                label.className = 'study-toggle';
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.checked = true;
                checkbox.dataset.idx = idx;
                
                checkbox.addEventListener('change', function() {
                    if (this.checked) {
                        excludedIndices.delete(idx);
                        label.classList.remove('excluded');
                    } else {
                        excludedIndices.add(idx);
                        label.classList.add('excluded');
                    }
                    recalculateAndRender();
                });
    
                const span = document.createElement('span');
                span.textContent = study.name;
    
                label.appendChild(checkbox);
                label.appendChild(span);
                container.appendChild(label);
            });
        }
    
        function recalculateAndRender() {
            const measure = document.getElementById('measureType').value;
            const model = document.getElementById('modelType').value;
            const swap = document.getElementById('swapGroups').checked;
    
            const activeStudies = globalStudies.filter((_, idx) => !excludedIndices.has(idx));
    
            if (activeStudies.length === 0) {
                document.getElementById('pooledEffect').innerText = "-";
                document.getElementById('pooledCI').innerText = "データなし";
                document.getElementById('pValue').innerText = "-";
                document.getElementById('i2Value').innerText = "-";
                document.getElementById('qValue').innerText = "-";
                Plotly.purge('plot-area'); 
                return;
            }
    
            const processedStudies = activeStudies.map(s => {
                let ne, me, se, nc, mc, sc;
                if (swap) {
                    ne = s.n2; me = s.m2; se = s.s2;
                    nc = s.n1; mc = s.m1; sc = s.s1;
                } else {
                    ne = s.n1; me = s.m1; se = s.s1;
                    nc = s.n2; mc = s.m2; sc = s.s2;
                }
                return { name: s.name, ne, me, se, nc, mc, sc };
            });
    
            let effects = [];
            let variances = [];
            
            processedStudies.forEach(s => {
                let es, v;
                if (measure === 'MD') {
                    es = s.me - s.mc;
                    v = (s.se * s.se / s.ne) + (s.sc * s.sc / s.nc);
                } else {
                    const sd_pooled = Math.sqrt(((s.ne - 1)*s.se*s.se + (s.nc - 1)*s.sc*s.sc) / (s.ne + s.nc - 2));
                    const cohen_d = (s.me - s.mc) / sd_pooled;
                    const correction = 1 - (3 / (4 * (s.ne + s.nc) - 9));
                    es = cohen_d * correction;
                    v = (s.ne + s.nc) / (s.ne * s.nc) + (es * es) / (2 * (s.ne + s.nc));
                }
                effects.push(es);
                variances.push(v);
            });
    
            let w_fixed = variances.map(v => 1/v);
            let sum_w = w_fixed.reduce((a,b)=>a+b, 0);
            let sum_wy = w_fixed.reduce((a,b,i) => a + b * effects[i], 0);
            let es_fixed = sum_wy / sum_w;
            
            let q = w_fixed.reduce((a, w, i) => a + w * Math.pow(effects[i] - es_fixed, 2), 0);
            let df = processedStudies.length - 1;
            let i2 = (df === 0 || q <= df) ? 0 : Math.max(0, (q - df) / q) * 100;
    
            let tau2 = 0;
            if (model === 'random' && df > 0) {
                let sum_w2 = w_fixed.reduce((a,b) => a + b*b, 0);
                let c = sum_w - (sum_w2 / sum_w);
                if (q > df && c > 0) tau2 = (q - df) / c;
            }
    
            let final_weights = variances.map(v => 1 / (v + tau2));
            let sum_fw = final_weights.reduce((a,b)=>a+b, 0);
            let sum_fwy = final_weights.reduce((a,b,i) => a + b * effects[i], 0);
            
            let pooledES = sum_fwy / sum_fw;
            let pooledSE = Math.sqrt(1 / sum_fw);
            let lowerCI = pooledES - 1.96 * pooledSE;
            let upperCI = pooledES + 1.96 * pooledSE;
            
            // p値計算 (jStat依存を排除し、自前の関数を使用)
            let z = Math.abs(pooledES / pooledSE);
            let pVal = Stats.calcTwoSidedP(z);
    
            document.getElementById('pooledEffect').innerText = pooledES.toFixed(3);
            document.getElementById('pooledCI').innerText = `95% CI: [${lowerCI.toFixed(3)}, ${upperCI.toFixed(3)}]`;
            document.getElementById('pValue').innerText = `p = ${pVal.toFixed(4)}`;
            document.getElementById('i2Value').innerText = `${i2.toFixed(1)}%`;
            document.getElementById('qValue').innerText = `Q = ${q.toFixed(2)} (df=${df})`;
    
            drawForestPlot(processedStudies, effects, variances, final_weights, pooledES, lowerCI, upperCI, measure, swap);
        }
    
        function drawForestPlot(studies, effects, variances, weights, pooledES, lowerCI, upperCI, measureLabel, isSwapped) {
            const studynames = studies.map(s => s.name);
            const ses = variances.map(v => Math.sqrt(v));
            
            let xTitle = measureLabel;
            if (isSwapped) {
                xTitle += " (Favors Control <--- | ---> Favors Treatment) [Swapped]";
            }
    
            const pooledName = 'Pooled Estimate';
            const yOrder = [pooledName].concat([...studynames].reverse());
    
            const traceStudies = {
                x: effects,
                y: studynames,
                error_x: {
                    type: 'data', array: ses.map(s => s * 1.96), visible: true, color: 'navy'
                },
                mode: 'markers', type: 'scatter', marker: { size: 10, symbol: 'square', color: 'navy' },
                name: 'Studies',
                hoverinfo: 'x+y'
            };
    
            const tracePooled = {
                x: [pooledES], y: [pooledName],
                error_x: {
                    type: 'data', array: [upperCI - pooledES], visible: true, color: 'red', width: 4
                },
                mode: 'markers', type: 'scatter', marker: { size: 14, symbol: 'diamond', color: 'red' },
                name: 'Pooled',
                hoverinfo: 'x+text',
                text: [`${pooledES.toFixed(3)} [${lowerCI.toFixed(3)}, ${upperCI.toFixed(3)}]`]
            };
    
            const layout = {
                title: `Forest Plot (${measureLabel})`,
                xaxis: { title: xTitle, zeroline: true, zerolinecolor: 'gray' },
                yaxis: { 
                    title: '', 
                    automargin: true,
                    categoryorder: 'array',
                    categoryarray: yOrder
                },
                height: Math.max(400, studies.length * 50 + 200),
                shapes: [
                    { type: 'line', x0: 0, x1: 0, y0: 0, y1: 1, xref: 'x', yref: 'paper', line: {color: 'grey', width: 1, dash: 'dash'} }
                ],
                hovermode: 'closest',
                margin: {l: 150, r: 50, t: 80, b: 80}
            };
    
            Plotly.newPlot('plot-area', [traceStudies, tracePooled], layout);
        }
    </script>
    
    </body>
    </html>
    




    絶対効果については?

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>GRADE Forest Plot Generator (Batch Input)</title>
        <style>
            :root {
                --primary: #2563eb;
                --primary-dark: #1d4ed8;
                --danger: #dc2626;
                --success: #16a34a;
                --warning: #f59e0b;
                --gray-50: #f9fafb;
                --gray-100: #f3f4f6;
                --gray-200: #e5e7eb;
                --gray-300: #d1d5db;
                --gray-500: #6b7280;
                --gray-700: #374151;
                --gray-900: #111827;
            }
    
            * {
                box-sizing: border-box;
                margin: 0;
                padding: 0;
            }
    
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                background: var(--gray-100);
                color: var(--gray-900);
                line-height: 1.6;
                padding-bottom: 40px;
            }
    
            .container {
                max-width: 1400px;
                margin: 0 auto;
                padding: 20px;
            }
    
            h1 {
                text-align: center;
                color: var(--gray-900);
                margin-bottom: 10px;
                font-size: 1.8rem;
            }
    
            .subtitle {
                text-align: center;
                color: var(--gray-500);
                margin-bottom: 30px;
                font-size: 0.95rem;
            }
    
            .card {
                background: white;
                border-radius: 12px;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                padding: 24px;
                margin-bottom: 20px;
            }
    
            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;
                padding-bottom: 10px;
                border-bottom: 2px solid var(--gray-200);
            }
    
            .card-title {
                font-size: 1.1rem;
                font-weight: 600;
                color: var(--gray-700);
                margin: 0;
            }
    
            .form-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 16px;
            }
    
            .form-group {
                display: flex;
                flex-direction: column;
            }
    
            .form-group label {
                font-size: 0.85rem;
                font-weight: 500;
                color: var(--gray-700);
                margin-bottom: 6px;
            }
    
            .form-group input, .form-group select, .form-group textarea {
                padding: 10px 12px;
                border: 1px solid var(--gray-300);
                border-radius: 8px;
                font-size: 0.95rem;
                transition: border-color 0.2s, box-shadow 0.2s;
            }
    
            .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
                outline: none;
                border-color: var(--primary);
                box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            }
    
            /* 重要性のスタイル */
            .imp-high { color: #dc2626; font-weight: bold; } /* 7-9 */
            .imp-mod { color: #d97706; font-weight: bold; }  /* 4-6 */
            .imp-low { color: #16a34a; font-weight: bold; }  /* 1-3 */
    
            .outcome-item {
                background: var(--gray-50);
                border: 1px solid var(--gray-200);
                border-radius: 10px;
                padding: 20px;
                margin-bottom: 16px;
            }
    
            .outcome-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16px;
            }
    
            .outcome-title {
                font-weight: 600;
                color: var(--gray-700);
                display: flex;
                align-items: center;
                gap: 10px;
            }
    
            .outcome-type-badge {
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 0.75rem;
                font-weight: 500;
            }
            
            .imp-badge {
                background: #fff;
                border: 1px solid #ccc;
                padding: 2px 8px;
                border-radius: 4px;
                font-size: 0.8rem;
            }
    
            .badge-dichotomous { background: #dbeafe; color: #1e40af; }
            .badge-continuous { background: #dcfce7; color: #166534; }
    
            .btn {
                padding: 10px 20px;
                border: none;
                border-radius: 8px;
                font-size: 0.95rem;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.2s;
                display: inline-flex;
                align-items: center;
                justify-content: center;
            }
    
            .btn:disabled { opacity: 0.6; cursor: not-allowed; }
            .btn-primary { background: var(--primary); color: white; }
            .btn-primary:hover:not(:disabled) { background: var(--primary-dark); }
            .btn-danger { background: var(--danger); color: white; }
            .btn-danger:hover:not(:disabled) { background: #b91c1c; }
            .btn-secondary { background: var(--gray-200); color: var(--gray-700); }
            .btn-secondary:hover:not(:disabled) { background: var(--gray-300); }
            .btn-sm { padding: 6px 12px; font-size: 0.85rem; }
    
            .btn-group {
                display: flex;
                gap: 10px;
                margin-top: 20px;
                flex-wrap: wrap;
            }
    
            .forest-plot-container {
                overflow-x: auto;
                padding: 20px 0;
                text-align: center;
            }
    
            .forest-plot {
                display: inline-block;
                min-width: 950px;
            }
    
            .legend {
                display: flex;
                gap: 24px;
                justify-content: center;
                flex-wrap: wrap;
                padding: 16px;
                background: var(--gray-50);
                border-radius: 8px;
                margin-top: 20px;
            }
    
            .legend-item {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 0.85rem;
            }
    
            .legend-color { width: 16px; height: 16px; border-radius: 3px; }
            .legend-color.benefit { background: var(--success); }
            .legend-color.harm { background: var(--danger); }
            .legend-color.neutral { background: var(--primary); }
            .legend-line { width: 24px; height: 0; border-top: 2px dashed var(--danger); }
    
            .download-options {
                display: flex;
                gap: 10px;
                justify-content: flex-end;
                margin-top: 20px;
            }
    
            .tab-container {
                display: flex;
                gap: 5px;
                margin-bottom: 20px;
            }
    
            .tab {
                padding: 10px 20px;
                border: none;
                background: var(--gray-200);
                border-radius: 8px 8px 0 0;
                cursor: pointer;
                font-weight: 500;
                color: var(--gray-600);
                transition: all 0.2s;
            }
    
            .tab.active {
                background: white;
                color: var(--primary);
                box-shadow: 0 -2px 5px rgba(0,0,0,0.05);
            }
    
            .direction-select { min-width: 120px; }
            .error-message { color: var(--danger); font-size: 0.85rem; margin-top: 5px; display: none; }
    
            /* バッチ入力エリア用 */
            .batch-area {
                font-family: monospace;
                line-height: 1.4;
            }
            
            /* 待機リスト用 */
            .pending-list {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 10px;
                margin-top: 15px;
            }
            .pending-item {
                background: #fff;
                border: 1px solid var(--primary);
                border-radius: 6px;
                padding: 10px;
                cursor: pointer;
                transition: all 0.2s;
                position: relative;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .pending-item:hover {
                background: #eff6ff;
                transform: translateY(-2px);
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .pending-name { font-weight: 600; font-size: 0.9rem; }
            .pending-score { 
                background: var(--gray-200); 
                padding: 2px 6px; 
                border-radius: 4px; 
                font-size: 0.8rem;
                margin-left: 8px;
            }
            .arrow-icon { color: var(--primary); font-weight: bold; }
    
            @media (max-width: 768px) {
                .form-grid { grid-template-columns: 1fr; }
                .btn-group { flex-direction: column; }
                .btn { width: 100%; }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>🏥 GRADE Forest Plot Generator</h1>
            <p class="subtitle">重要性と絶対効果を含む包括的プロット作成ツール</p>
    
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">📋 研究基本情報</h2>
                </div>
                <div class="form-grid">
                    <div class="form-group">
                        <label>研究タイトル / 課題</label>
                        <input type="text" id="studyTitle" placeholder="例: ○○介入の効果">
                    </div>
                    <div class="form-group">
                        <label>対照群の人数(換算用)</label>
                        <input type="number" id="populationSize" value="1000" min="100" step="100">
                        <span class="error-message">正の整数を入力してください</span>
                    </div>
                </div>
            </div>
    
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">🚀 ステップ1: アウトカムの一括登録(リスト作成)</h2>
                </div>
                <div class="form-group">
                    <label>アウトカム名と重要性(1-9)を1行ずつ入力してください</label>
                    <textarea id="batchInput" class="batch-area" rows="4" placeholder="(例)&#13;&#10;全死亡 9&#13;&#10;心筋梗塞 8&#13;&#10;重篤な有害事象 7&#13;&#10;入院期間 5"></textarea>
                    <small style="color: var(--gray-500);">※ 「名前」と「数値」の間はスペースまたはカンマで区切ってください</small>
                </div>
                <div class="btn-group">
                    <button class="btn btn-secondary" onclick="parseBatchInput()">⬇️ リストに取り込む</button>
                </div>
    
                <div id="pendingContainer" style="display:none; margin-top: 20px; border-top: 1px solid var(--gray-200); padding-top: 20px;">
                    <h3 style="font-size: 1rem; color: var(--gray-700); margin-bottom: 10px;">👇 詳細入力待ちリスト(クリックして入力)</h3>
                    <div id="pendingList" class="pending-list"></div>
                </div>
            </div>
    
            <div class="card" id="inputFormCard">
                <div class="card-header">
                    <h2 class="card-title">✍️ ステップ2: 詳細データの入力</h2>
                </div>
                
                <div class="tab-container">
                    <button class="tab active" onclick="switchTab('dichotomous')">二値アウトカム(RR/OR)</button>
                    <button class="tab" onclick="switchTab('continuous')">連続量アウトカム(MD)</button>
                </div>
    
                <div id="dichotomousForm">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>アウトカム名 <span style="color:red">*</span></label>
                            <input type="text" id="outcomeName" placeholder="例: 死亡">
                        </div>
                        <div class="form-group">
                            <label>重要性 (1-9点) <span style="color:red">*</span></label>
                            <input type="number" id="importance" min="1" max="9" step="1" placeholder="9">
                        </div>
                        <div class="form-group">
                            <label>ユーティリティ (0.0-1.0)</label>
                            <input type="number" id="utility" step="0.1" min="0" max="1" placeholder="例: 0.8">
                        </div>
                    </div>
    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>効果指標</label>
                            <select id="effectMeasure">
                                <option value="RR">相対リスク (RR)</option>
                                <option value="OR">オッズ比 (OR)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>望ましい方向</label>
                            <select id="desirableDirection" class="direction-select">
                                <option value="lower">低下が望ましい (例: 死亡)</option>
                                <option value="higher">増加が望ましい (例: 治癒)</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>点推定値 <span style="color:red">*</span></label>
                            <input type="number" id="pointEstimate" step="0.01" placeholder="例: 0.75">
                        </div>
                        <div class="form-group">
                            <label>95% CI 下限 <span style="color:red">*</span></label>
                            <input type="number" id="ciLower" step="0.01" placeholder="例: 0.60">
                        </div>
                        <div class="form-group">
                            <label>95% CI 上限 <span style="color:red">*</span></label>
                            <input type="number" id="ciUpper" step="0.01" placeholder="例: 0.95">
                        </div>
                    </div>
    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>ベースラインリスク (/1000人) <span style="color:red">*</span></label>
                            <input type="number" id="baselineRisk" step="0.1" placeholder="例: 50">
                        </div>
                        <div class="form-group">
                            <label>MID(最小重要差, 絶対数)</label>
                            <input type="number" id="midValue" step="0.1" placeholder="オプション">
                        </div>
                    </div>
                </div>
    
                <div id="continuousForm" style="display: none;">
                    <div class="form-grid">
                        <div class="form-group">
                            <label>アウトカム名 <span style="color:red">*</span></label>
                            <input type="text" id="contOutcomeName" placeholder="例: QOLスコア">
                        </div>
                        <div class="form-group">
                            <label>重要性 (1-9点) <span style="color:red">*</span></label>
                            <input type="number" id="contImportance" min="1" max="9" step="1" placeholder="9">
                        </div>
                        <div class="form-group">
                            <label>ユーティリティ (0.0-1.0)</label>
                            <input type="number" id="contUtility" step="0.1" min="0" max="1" placeholder="例: 0.8">
                        </div>
                    </div>
                    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>単位 <span style="color:red">*</span></label>
                            <input type="text" id="contUnit" placeholder="例: 点, mmHg">
                        </div>
                        <div class="form-group">
                            <label>望ましい方向</label>
                            <select id="contDesirableDirection" class="direction-select">
                                <option value="higher">増加が望ましい (例: 点数)</option>
                                <option value="lower">低下が望ましい (例: 疼痛)</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>平均差(MD)点推定値 <span style="color:red">*</span></label>
                            <input type="number" id="contPointEstimate" step="0.01" placeholder="例: 5.2">
                        </div>
                        <div class="form-group">
                            <label>95% CI 下限 <span style="color:red">*</span></label>
                            <input type="number" id="contCiLower" step="0.01" placeholder="例: 2.1">
                        </div>
                        <div class="form-group">
                            <label>95% CI 上限 <span style="color:red">*</span></label>
                            <input type="number" id="contCiUpper" step="0.01" placeholder="例: 8.3">
                        </div>
                    </div>
    
                    <div class="form-grid" style="margin-top: 16px;">
                        <div class="form-group">
                            <label>MID(最小重要差)</label>
                            <input type="number" id="contMidValue" step="0.01" placeholder="オプション">
                        </div>
                    </div>
                </div>
    
                <div class="btn-group">
                    <button class="btn btn-primary" onclick="addOutcome()">➕ アウトカムを追加</button>
                </div>
            </div>
    
            <div class="card" id="outcomesCard" style="display: none;">
                <div class="card-header">
                    <h2 class="card-title">📝 追加済みアウトカム</h2>
                </div>
                <div id="outcomesList"></div>
                <div class="btn-group">
                    <button class="btn btn-primary" onclick="generatePlot()">📊 フォレストプロット生成/更新</button>
                    <button class="btn btn-danger" onclick="clearAllOutcomes()">🗑️ すべてクリア</button>
                </div>
            </div>
    
            <div class="card" id="plotCard" style="display: none;">
                <div class="card-header">
                    <h2 class="card-title">🌲 フォレストプロット</h2>
                </div>
                <div id="plotTitle" style="text-align: center; font-weight: 600; margin-bottom: 20px; font-size: 1.2rem;"></div>
                
                <div class="forest-plot-container">
                    <div class="forest-plot" id="forestPlot"></div>
                </div>
    
                <div class="legend">
                    <div class="legend-item">
                        <div class="legend-color benefit"></div>
                        <span>有益(MID超過)</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color harm"></div>
                        <span>有害(MID超過)</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color neutral"></div>
                        <span>不確実/MID未満</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-line"></div>
                        <span>MIDライン</span>
                    </div>
                </div>
    
                <div class="download-options">
                    <button class="btn btn-secondary" onclick="downloadAsSVG()">📥 SVG保存</button>
                    <button class="btn btn-secondary" onclick="downloadAsPNG()">📥 PNG保存</button>
                </div>
            </div>
        </div>
    
        <script>
            // 状態管理
            let outcomes = [];
            let pendingQueue = []; // 待機リスト
            let currentTab = 'dichotomous';
    
            // 初期化処理
            document.addEventListener('DOMContentLoaded', () => {
                // 必要に応じて初期化処理
            });
    
            // タブ切り替え
            function switchTab(tab) {
                currentTab = tab;
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                const target = event.currentTarget || event.target;
                target.classList.add('active');
                document.getElementById('dichotomousForm').style.display = tab === 'dichotomous' ? 'block' : 'none';
                document.getElementById('continuousForm').style.display = tab === 'continuous' ? 'block' : 'none';
            }
    
            // バッチ入力の解析
            function parseBatchInput() {
                const rawText = document.getElementById('batchInput').value;
                if (!rawText.trim()) {
                    alert("テキストエリアにアウトカム名と数値を入力してください。");
                    return;
                }
    
                const lines = rawText.split('\n');
                let addedCount = 0;
    
                lines.forEach(line => {
                    line = line.trim();
                    if (!line) return;
    
                    // 正規表現: 末尾の1桁の数字(1-9)を重要性として抽出
                    // 例: "全死亡 9" -> name="全死亡", score="9"
                    // 例: "入院, 5" -> name="入院", score="5"
                    const match = line.match(/^(.+?)[\s,、\t]+([1-9])$/);
                    
                    if (match) {
                        const name = match[1].trim();
                        const score = parseInt(match[2]);
                        
                        pendingQueue.push({
                            id: Date.now() + Math.random(),
                            name: name,
                            importance: score
                        });
                        addedCount++;
                    } else {
                        // 数字が見つからない場合は名前だけで重要性は空欄扱い、またはスキップ
                        // ここでは名前だけ登録して重要性はデフォルトにする簡易対応も可能だが
                        // ユーザーに修正を促すため、スキップするか、名前のみ登録する。
                        // 今回は「名前だけ」のパターンも許容する(重要性は手入力)
                        if (line.length > 0) {
                             pendingQueue.push({
                                id: Date.now() + Math.random(),
                                name: line,
                                importance: null // 後で入力
                            });
                            addedCount++;
                        }
                    }
                });
    
                document.getElementById('batchInput').value = ''; // クリア
                renderPendingQueue();
                
                if (addedCount > 0) {
                    document.getElementById('pendingContainer').style.display = 'block';
                }
            }
    
            // 待機リストの描画
            function renderPendingQueue() {
                const container = document.getElementById('pendingList');
                const wrapper = document.getElementById('pendingContainer');
    
                if (pendingQueue.length === 0) {
                    wrapper.style.display = 'none';
                    return;
                }
    
                wrapper.style.display = 'block';
                container.innerHTML = pendingQueue.map((item, index) => {
                    const scoreDisplay = item.importance ? `重要性: ${item.importance}` : '重要性: 未設定';
                    return `
                        <div class="pending-item" onclick="loadFromQueue(${index})">
                            <div>
                                <span class="pending-name">${escapeHtml(item.name)}</span>
                                <span class="pending-score">${scoreDisplay}</span>
                            </div>
                            <span class="arrow-icon">入力 ➡️</span>
                        </div>
                    `;
                }).join('');
            }
    
            // 待機リストからフォームへロード
            function loadFromQueue(index) {
                const item = pendingQueue[index];
                
                // フォームにセット
                if (currentTab === 'dichotomous') {
                    document.getElementById('outcomeName').value = item.name;
                    if (item.importance) document.getElementById('importance').value = item.importance;
                } else {
                    document.getElementById('contOutcomeName').value = item.name;
                    if (item.importance) document.getElementById('contImportance').value = item.importance;
                }
    
                // 待機リストから削除
                pendingQueue.splice(index, 1);
                renderPendingQueue();
    
                // フォームへスクロール
                document.getElementById('inputFormCard').scrollIntoView({ behavior: 'smooth' });
                
                // 該当フィールドを強調
                const nameField = currentTab === 'dichotomous' ? document.getElementById('outcomeName') : document.getElementById('contOutcomeName');
                nameField.focus();
            }
    
            // ヘルパー関数群
            function getVal(id) {
                const el = document.getElementById(id);
                const val = el.value.trim();
                if (val === '') return NaN;
                return parseFloat(val);
            }
    
            function getStr(id) {
                return document.getElementById(id).value.trim();
            }
    
            function getPopSize() {
                let val = parseInt(document.getElementById('populationSize').value);
                return (isNaN(val) || val <= 0) ? 1000 : val;
            }
    
            // アウトカム追加処理
            function addOutcome() {
                let outcome;
                
                try {
                    if (currentTab === 'dichotomous') {
                        const name = getStr('outcomeName');
                        const importance = getVal('importance');
                        const utility = getVal('utility');
                        const measure = getStr('effectMeasure');
                        const direction = getStr('desirableDirection');
                        const point = getVal('pointEstimate');
                        const lower = getVal('ciLower');
                        const upper = getVal('ciUpper');
                        const baseline = getVal('baselineRisk');
                        const mid = getVal('midValue');
    
                        if (!name) throw new Error('アウトカム名を入力してください');
                        if (isNaN(importance) || importance < 1 || importance > 9 || !Number.isInteger(importance)) {
                            throw new Error('重要性は1〜9の整数で入力してください');
                        }
                        if (!isNaN(utility) && (utility < 0 || utility > 1)) {
                            throw new Error('ユーティリティは0.0〜1.0の間で入力してください');
                        }
                        if (isNaN(point) || isNaN(lower) || isNaN(upper)) throw new Error('効果推定値をすべて入力してください');
                        if (isNaN(baseline)) throw new Error('ベースラインリスクを入力してください');
                        if (lower > upper) throw new Error('信頼区間の下限が上限より大きくなっています');
    
                        outcome = {
                            type: 'dichotomous',
                            id: Date.now(),
                            name, importance, utility: isNaN(utility) ? null : utility,
                            measure, direction, point, lower, upper, baseline,
                            mid: isNaN(mid) ? null : mid
                        };
    
                        // フォームクリア
                        ['outcomeName', 'importance', 'utility', 'pointEstimate', 'ciLower', 'ciUpper', 'baselineRisk', 'midValue']
                            .forEach(id => document.getElementById(id).value = '');
    
                    } else {
                        const name = getStr('contOutcomeName');
                        const importance = getVal('contImportance');
                        const utility = getVal('contUtility');
                        const unit = getStr('contUnit');
                        const direction = getStr('contDesirableDirection');
                        const point = getVal('contPointEstimate');
                        const lower = getVal('contCiLower');
                        const upper = getVal('contCiUpper');
                        const mid = getVal('contMidValue');
    
                        if (!name) throw new Error('アウトカム名を入力してください');
                        if (isNaN(importance) || importance < 1 || importance > 9 || !Number.isInteger(importance)) {
                            throw new Error('重要性は1〜9の整数で入力してください');
                        }
                        if (!unit) throw new Error('単位を入力してください');
                        if (isNaN(point) || isNaN(lower) || isNaN(upper)) throw new Error('推定値をすべて入力してください');
                        if (lower > upper) throw new Error('信頼区間の下限が上限より大きくなっています');
    
                        outcome = {
                            type: 'continuous',
                            id: Date.now(),
                            name, importance, utility: isNaN(utility) ? null : utility,
                            unit, direction, point, lower, upper,
                            mid: isNaN(mid) ? null : mid
                        };
    
                        // フォームクリア
                        ['contOutcomeName', 'contImportance', 'contUtility', 'contUnit', 'contPointEstimate', 'contCiLower', 'contCiUpper', 'contMidValue']
                            .forEach(id => document.getElementById(id).value = '');
                    }
    
                    outcomes.push(outcome);
                    renderOutcomesList();
    
                    // 待機リストがまだ残っていれば表示
                    if (pendingQueue.length > 0) {
                        document.getElementById('pendingContainer').scrollIntoView({ behavior: 'smooth' });
                    }
    
                } catch (e) {
                    alert(e.message);
                }
            }
    
            // アウトカムリスト描画
            function renderOutcomesList() {
                const container = document.getElementById('outcomesList');
                const card = document.getElementById('outcomesCard');
                const popSize = getPopSize();
                
                if (outcomes.length === 0) {
                    card.style.display = 'none';
                    document.getElementById('plotCard').style.display = 'none';
                    return;
                }
                
                card.style.display = 'block';
                
                container.innerHTML = outcomes.map((o, i) => {
                    const utilStr = o.utility !== null ? `Util: ${o.utility.toFixed(1)}` : '';
                    const impClass = o.importance >= 7 ? 'imp-high' : (o.importance >= 4 ? 'imp-mod' : 'imp-low');
                    
                    if (o.type === 'dichotomous') {
                        const abs = calculateAbsoluteEffect(o, popSize);
                        return `
                            <div class="outcome-item">
                                <div class="outcome-header">
                                    <span class="outcome-title">
                                        ${escapeHtml(o.name)}
                                        <span class="imp-badge ${impClass}">重要性: ${o.importance}</span>
                                    </span>
                                    <span class="outcome-type-badge badge-dichotomous">${o.measure}</span>
                                </div>
                                <div class="form-grid">
                                    ${utilStr ? `<div><strong>ユーティリティ:</strong> ${o.utility.toFixed(1)}</div>` : ''}
                                    <div><strong>相対効果:</strong> ${o.point} (${o.lower} - ${o.upper})</div>
                                    <div><strong>ベースライン:</strong> ${o.baseline}/1000人</div>
                                    <div><strong>絶対効果 (/${popSize}人):</strong> ${abs.pointStr} (${Math.round(abs.lower)} to ${Math.round(abs.upper)})</div>
                                    ${o.mid ? `<div><strong>MID:</strong> ±${o.mid}人</div>` : ''}
                                </div>
                                <button class="btn btn-danger btn-sm" style="margin-top: 12px;" onclick="removeOutcome(${i})">削除</button>
                            </div>
                        `;
                    } else {
                        return `
                            <div class="outcome-item">
                                <div class="outcome-header">
                                    <span class="outcome-title">
                                        ${escapeHtml(o.name)}
                                        <span class="imp-badge ${impClass}">重要性: ${o.importance}</span>
                                    </span>
                                    <span class="outcome-type-badge badge-continuous">連続量</span>
                                </div>
                                <div class="form-grid">
                                    ${utilStr ? `<div><strong>ユーティリティ:</strong> ${o.utility.toFixed(1)}</div>` : ''}
                                    <div><strong>平均差 (MD):</strong> ${o.point} ${escapeHtml(o.unit)}</div>
                                    <div><strong>95% CI:</strong> ${o.lower} - ${o.upper}</div>
                                    ${o.mid ? `<div><strong>MID:</strong> ±${o.mid}</div>` : ''}
                                </div>
                                <button class="btn btn-danger btn-sm" style="margin-top: 12px;" onclick="removeOutcome(${i})">削除</button>
                            </div>
                        `;
                    }
                }).join('');
            }
    
            // XSS対策
            function escapeHtml(str) {
                if(!str) return '';
                return str.replace(/[&<>"']/g, function(m) {
                    return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[m];
                });
            }
    
            // 絶対効果計算
            function calculateAbsoluteEffect(outcome, popSize) {
                const scaleFactor = popSize / 1000;
                const baselineScaled = outcome.baseline * scaleFactor;
                
                let pointEffect, lowerEffect, upperEffect;
                
                if (outcome.measure === 'RR') {
                    pointEffect = baselineScaled * (outcome.point - 1);
                    lowerEffect = baselineScaled * (outcome.lower - 1);
                    upperEffect = baselineScaled * (outcome.upper - 1);
                } else { // OR
                    const blProb = outcome.baseline / 1000;
                    const blOdds = blProb / (1 - blProb);
                    
                    const calcRiskDiff = (oddsRatio) => {
                        const postOdds = blOdds * oddsRatio;
                        const postProb = postOdds / (1 + postOdds);
                        return (postProb * popSize) - baselineScaled;
                    };
    
                    pointEffect = calcRiskDiff(outcome.point);
                    lowerEffect = calcRiskDiff(outcome.lower);
                    upperEffect = calcRiskDiff(outcome.upper);
                }
                
                const finalLower = Math.min(lowerEffect, upperEffect);
                const finalUpper = Math.max(lowerEffect, upperEffect);
    
                return {
                    point: pointEffect,
                    lower: finalLower,
                    upper: finalUpper,
                    pointStr: pointEffect > 0 ? `+${Math.round(pointEffect)}` : `${Math.round(pointEffect)}`
                };
            }
    
            function removeOutcome(index) {
                outcomes.splice(index, 1);
                renderOutcomesList();
                if (document.getElementById('plotCard').style.display === 'block') {
                    generatePlot();
                }
            }
    
            function clearAllOutcomes() {
                if (confirm('すべてのアウトカムを削除しますか?')) {
                    outcomes = [];
                    renderOutcomesList();
                }
            }
    
            // プロット生成
            function generatePlot() {
                if (outcomes.length === 0) return;
    
                const popSize = getPopSize();
                const plotCard = document.getElementById('plotCard');
                const plotContainer = document.getElementById('forestPlot');
                const studyTitle = getStr('studyTitle') || '効果のフォレストプロット';
    
                document.getElementById('plotTitle').textContent = studyTitle;
                plotCard.style.display = 'block';
    
                const plotData = outcomes.map(o => {
                    if (o.type === 'dichotomous') {
                        const abs = calculateAbsoluteEffect(o, popSize);
                        return { ...o, absData: abs, isDichotomous: true };
                    }
                    return { ...o, isDichotomous: false };
                });
    
                // スケール計算
                let dichMax = 0;
                let contMax = 0;
    
                plotData.forEach(d => {
                    if (d.isDichotomous) {
                        dichMax = Math.max(dichMax, Math.abs(d.absData.lower), Math.abs(d.absData.upper));
                        if(d.mid) dichMax = Math.max(dichMax, d.mid);
                    } else {
                        contMax = Math.max(contMax, Math.abs(d.lower), Math.abs(d.upper));
                        if(d.mid) contMax = Math.max(contMax, d.mid);
                    }
                });
    
                const dichRange = Math.max(dichMax * 1.2, 10); 
                const contRange = Math.max(contMax * 1.2, 1);
    
                // SVG設定
                const svgWidth = 950;
                const headerHeight = 50;
                const rowHeight = 60;
                const footerHeight = 40;
                const svgHeight = headerHeight + (outcomes.length * rowHeight) + footerHeight;
                
                const colNameX = 15;
                const colImpX = 180;
                const colUnitX = 250;
                const plotLeft = 350;
                const plotRight = 750;
                const plotWidth = plotRight - plotLeft;
                const centerX = plotLeft + (plotWidth / 2);
                const colEffectX = svgWidth - 15;
    
                const getX = (val, isDichotomous) => {
                    const range = isDichotomous ? dichRange : contRange;
                    if (range < 0.0001) return centerX;
                    return centerX + (val / range) * (plotWidth / 2);
                };
    
                let svg = `
                    <svg width="${svgWidth}" height="${svgHeight}" xmlns="http://www.w3.org/2000/svg" id="forestPlotSVG" style="font-family: sans-serif;">
                        <style>
                            text { font-family: sans-serif; }
                            .header { font-weight: bold; font-size: 13px; fill: #374151; }
                            .label { font-size: 13px; fill: #111827; }
                            .imp-val { font-size: 13px; font-weight: bold; }
                            .meta { font-size: 11px; fill: #6b7280; }
                            .val { font-weight: bold; font-size: 12px; fill: #111827; }
                            .ci { font-size: 11px; fill: #4b5563; }
                            .axis { font-size: 10px; fill: #6b7280; }
                        </style>
                        <rect width="100%" height="100%" fill="white"/>
                        
                        <rect x="0" y="0" width="${svgWidth}" height="${headerHeight}" fill="#f3f4f6"/>
                        <line x1="0" y1="${headerHeight}" x2="${svgWidth}" y2="${headerHeight}" stroke="#d1d5db" stroke-width="1"/>
    
                        <text x="${colNameX}" y="30" class="header">アウトカム</text>
                        <text x="${colImpX}" y="30" class="header">重要性</text>
                        <text x="${colUnitX}" y="30" class="header" text-anchor="end">基準/単位</text>
                        <text x="${centerX}" y="30" class="header" text-anchor="middle">絶対効果 / 平均差</text>
                        <text x="${colEffectX}" y="30" class="header" text-anchor="end">推定値 [95% CI]</text>
    
                        <line x1="${centerX}" y1="${headerHeight + 10}" x2="${centerX}" y2="${svgHeight - footerHeight}" stroke="#9ca3af" stroke-width="1" stroke-dasharray="4,2"/>
                `;
    
                plotData.forEach((d, i) => {
                    const y = headerHeight + (i * rowHeight) + (rowHeight / 2);
                    const rowTop = headerHeight + (i * rowHeight);
                    const rowBottom = rowTop + rowHeight;
                    
                    if (i % 2 === 1) {
                        svg += `<rect x="0" y="${rowTop}" width="${svgWidth}" height="${rowHeight}" fill="#f9fafb" fill-opacity="0.5"/>`;
                    }
    
                    let point, low, high, mid, unitStr, valText, ciText;
                    
                    if (d.isDichotomous) {
                        point = d.absData.point;
                        low = d.absData.lower;
                        high = d.absData.upper;
                        mid = d.mid;
                        unitStr = `${d.baseline}/1000人`;
                        valText = `${d.absData.pointStr} /${popSize}人`;
                        ciText = `[${Math.round(low)} to ${Math.round(high)}]`;
                    } else {
                        point = d.point;
                        low = d.lower;
                        high = d.upper;
                        mid = d.mid;
                        unitStr = d.unit;
                        valText = `${point > 0 ? '+' : ''}${point} ${d.unit}`;
                        ciText = `[${low} to ${high}]`;
                    }
    
                    let color = '#2563eb';
                    if (mid && Math.abs(point) >= mid) {
                        if ((d.direction === 'lower' && point < 0) || (d.direction === 'higher' && point > 0)) color = '#16a34a';
                        else color = '#dc2626';
                    }
    
                    const impColor = d.importance >= 7 ? '#dc2626' : (d.importance >= 4 ? '#d97706' : '#16a34a');
    
                    if (mid) {
                        const mx1 = getX(mid, d.isDichotomous);
                        const mx2 = getX(-mid, d.isDichotomous);
                        svg += `
                            <line x1="${mx1}" y1="${rowTop+5}" x2="${mx1}" y2="${rowBottom-5}" stroke="#dc2626" stroke-width="1" stroke-dasharray="2,2" opacity="0.5"/>
                            <line x1="${mx2}" y1="${rowTop+5}" x2="${mx2}" y2="${rowBottom-5}" stroke="#dc2626" stroke-width="1" stroke-dasharray="2,2" opacity="0.5"/>
                        `;
                    }
    
                    const x1 = getX(low, d.isDichotomous);
                    const x2 = getX(high, d.isDichotomous);
                    const xp = getX(point, d.isDichotomous);
    
                    svg += `<line x1="${x1}" y1="${y}" x2="${x2}" y2="${y}" stroke="${color}" stroke-width="2.5"/>`;
                    svg += `<line x1="${x1}" y1="${y-4}" x2="${x1}" y2="${y+4}" stroke="${color}" stroke-width="2.5"/>`;
                    svg += `<line x1="${x2}" y1="${y-4}" x2="${x2}" y2="${y+4}" stroke="${color}" stroke-width="2.5"/>`;
                    svg += `<rect x="${xp-5}" y="${y-5}" width="10" height="10" fill="${color}"/>`;
    
                    svg += `
                        <text x="${colNameX}" y="${y+4}" class="label">${escapeHtml(d.name)}</text>
                        <text x="${colImpX}" y="${y+4}" class="imp-val" fill="${impColor}" text-anchor="middle">${d.importance}</text>
                        <text x="${colUnitX}" y="${y+4}" class="meta" text-anchor="end">${escapeHtml(unitStr)}</text>
                        <text x="${colEffectX}" y="${y-6}" class="val" text-anchor="end">${valText}</text>
                        <text x="${colEffectX}" y="${y+9}" class="ci" text-anchor="end">${ciText}</text>
                    `;
                });
    
                svg += `
                    <text x="${plotLeft}" y="${svgHeight - 15}" class="axis">← 減少</text>
                    <text x="${plotRight}" y="${svgHeight - 15}" class="axis" text-anchor="end">増加 →</text>
                `;
    
                svg += '</svg>';
                plotContainer.innerHTML = svg;
                
                const popInput = document.getElementById('populationSize');
                popInput.onchange = () => {
                    if(outcomes.length > 0) {
                        renderOutcomesList();
                        generatePlot();
                    }
                };
                
                plotCard.scrollIntoView({ behavior: 'smooth' });
            }
    
            function downloadAsSVG() {
                const svgEl = document.getElementById('forestPlotSVG');
                if (!svgEl) return;
                const serializer = new XMLSerializer();
                let source = serializer.serializeToString(svgEl);
                if(!source.match(/^<xml/)) source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
                const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);
                const a = document.createElement('a');
                a.href = url;
                a.download = `forest_plot_${Date.now()}.svg`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
    
            function downloadAsPNG() {
                const svgEl = document.getElementById('forestPlotSVG');
                if (!svgEl) return;
                const serializer = new XMLSerializer();
                const source = serializer.serializeToString(svgEl);
                const svgBlob = new Blob([source], {type: "image/svg+xml;charset=utf-8"});
                const url = URL.createObjectURL(svgBlob);
                const canvas = document.createElement('canvas');
                const scale = 2;
                canvas.width = svgEl.width.baseVal.value * scale;
                canvas.height = svgEl.height.baseVal.value * scale;
                const ctx = canvas.getContext('2d');
                const img = new Image();
                img.onload = function() {
                    ctx.fillStyle = "white";
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    ctx.scale(scale, scale);
                    ctx.drawImage(img, 0, 0);
                    const pngUrl = canvas.toDataURL("image/png");
                    const a = document.createElement('a');
                    a.href = pngUrl;
                    a.download = `forest_plot_${Date.now()}.png`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                };
                img.src = url;
            }
        </script>
    </body>
    </html>

    CoreGRADE評価補助ソフト

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Core GRADE Master v20.1: Enhanced Explanations</title>
        <style>
            :root {
                --primary: #005a9c;
                --primary-dark: #003d69;
                --accent: #d32f2f;
                --warning: #f57f17;
                --success: #2e7d32;
                --bg-color: #f0f4f8;
                --text-main: #212121;
                --border: #d1d5db;
                --white: #ffffff;
            }
    
            * { box-sizing: border-box; }
    
            body {
                font-family: "Helvetica Neue", Arial, "Hiragino Kaku Gothic ProN", Meiryo, sans-serif;
                background-color: var(--bg-color);
                color: var(--text-main);
                margin: 0;
                padding: 0;
                line-height: 1.7;
            }
    
            .app-container {
                display: grid;
                grid-template-columns: 300px 1fr;
                height: 100vh;
                overflow: hidden;
            }
    
            /* Sidebar */
            .sidebar {
                background: var(--white);
                border-right: 1px solid var(--border);
                display: flex;
                flex-direction: column;
                box-shadow: 2px 0 15px rgba(0,0,0,0.05);
                z-index: 10;
            }
            .logo-area {
                padding: 20px;
                background: linear-gradient(135deg, var(--primary), var(--primary-dark));
                color: white;
            }
            .logo-title { font-size: 1.3em; font-weight: 800; margin: 0; }
            .logo-sub { font-size: 0.75em; opacity: 0.9; margin-top: 5px; }
    
            .nav-list { flex: 1; overflow-y: auto; padding: 10px; }
            .nav-group-title {
                font-size: 0.7em; font-weight: bold; color: #888;
                margin: 12px 0 5px 8px; text-transform: uppercase;
            }
            .nav-item {
                padding: 10px 12px;
                margin-bottom: 3px; cursor: pointer;
                border-radius: 6px; font-weight: 600; color: #546e7a;
                display: flex; align-items: center; transition: all 0.2s;
                font-size: 0.9em;
            }
            .nav-item:hover { background-color: #e3f2fd; color: var(--primary); }
            .nav-item.active { background-color: #e3f2fd; color: var(--primary-dark);
                border-left: 4px solid var(--primary); }
            .nav-icon { margin-right: 10px; }
            .nav-badge { margin-left: auto; background: var(--accent); color: white; font-size: 0.65em; padding: 2px 6px; border-radius: 10px; }
    
            /* Main Content */
            .main-content {
                padding: 30px 50px;
                overflow-y: auto;
            }
    
            .section { display: none; animation: fadeIn 0.3s ease; }
            .section.active { display: block; }
            @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    
            h2 { font-size: 1.8em; color: var(--primary-dark); margin-top: 0;
                border-bottom: 3px solid var(--border); padding-bottom: 12px; }
            h3 { font-size: 1.3em; color: #37474f; margin-top: 30px;
                border-left: 5px solid var(--primary); padding-left: 12px; }
            h4 { color: var(--primary); margin-top: 20px; font-size: 1.1em; }
    
            /* Deep Dive & Explanations */
            .deep-dive {
                background: var(--white);
                border: 1px solid #90caf9;
                border-radius: 8px; margin: 20px 0;
                box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            }
            .deep-dive summary {
                background: #e3f2fd; padding: 15px 20px;
                cursor: pointer;
                font-weight: bold; color: var(--primary-dark);
                list-style: none; font-size: 1em;
            }
            .deep-dive summary::before { content: "📘 "; }
            .deep-dive summary:hover { background: #bbdefb; }
            
            .deep-content {
                padding: 25px;
                font-size: 0.92em; line-height: 1.85; color: #37474f;
                border-top: 1px solid #90caf9;
            }
            .deep-content h5 { color: var(--primary);
                font-size: 1.1em; margin: 25px 0 10px 0; border-bottom: 1px dashed #ccc; padding-bottom: 5px;
            }
            
            .guyatt-box { background: #f3e5f5;
                border-left: 5px solid #7b1fa2; padding: 12px 15px; margin: 15px 0; color: #4a148c; border-radius: 0 6px 6px 0;
            }
            .pitfall { background: #ffebee;
                border-left: 5px solid var(--accent); padding: 12px 15px; margin: 15px 0; color: #b71c1c; border-radius: 0 6px 6px 0;
            }
            .guidance { background: #e8f5e9; border-left: 5px solid var(--success); padding: 12px 15px; margin: 15px 0; color: #1b5e20;
                border-radius: 0 6px 6px 0; }
            .info-box { background: #fff3e0; border-left: 5px solid var(--warning); padding: 12px 15px;
                margin: 15px 0; color: #e65100; border-radius: 0 6px 6px 0; }
            
            .flow-step { display: flex; margin-bottom: 12px; align-items: flex-start; }
            .flow-num { background: var(--primary); color: white; min-width: 24px; height: 24px; line-height: 24px; border-radius: 50%; text-align: center;
                margin-right: 10px; font-size: 0.85em; font-weight: bold; flex-shrink: 0; }
    
            /* UI Components */
            .card {
                background: var(--white);
                padding: 25px; border-radius: 10px;
                box-shadow: 0 3px 15px rgba(0,0,0,0.07); border: 1px solid #e0e0e0;
                margin-bottom: 25px;
            }
            .card-highlight { border: 2px solid var(--primary); }
            .card-info { background: #e3f2fd; border: none; }
    
            .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; }
            .form-grid-2 { grid-template-columns: repeat(2, 1fr); }
            .form-grid-3 { grid-template-columns: repeat(3, 1fr); }
            .form-grid-6 { grid-template-columns: repeat(6, 1fr); }
    
            label { display: block; font-weight: bold; margin-bottom: 6px; color: #546e7a; font-size: 0.88em; }
            input, select, textarea {
                width: 100%; padding: 10px;
                border: 1px solid #cfd8dc; border-radius: 5px; font-size: 0.95em;
            }
            input:focus, select:focus, textarea:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 2px rgba(0,90,156,0.1); }
            
            .btn {
                background: var(--primary); color: white; padding: 10px 20px;
                border: none; border-radius: 5px; cursor: pointer;
                font-size: 0.95em; font-weight: bold; transition: 0.2s;
            }
            .btn:hover { background: var(--primary-dark); }
            .btn-outline { background: transparent; border: 2px solid var(--primary); color: var(--primary); }
            .btn-outline:hover { background: #e3f2fd; }
            .btn-success { background: var(--success); }
            .btn-group { display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap; }
    
            .outcome-card {
                background: white; border: 1px solid #ddd; padding: 12px 15px;
                border-radius: 6px; margin-bottom: 8px; cursor: pointer;
                display: flex; justify-content: space-between; align-items: center; transition: all 0.2s;
            }
            .outcome-card:hover { border-color: var(--primary); box-shadow: 0 2px 6px rgba(0,0,0,0.1); }
            .outcome-card.selected { border-color: var(--primary); background: #e3f2fd; }
            .outcome-badge { font-size: 0.75em; padding: 2px 8px; border-radius: 10px; }
            .badge-critical { background: #ffcdd2; color: #c62828; }
            .badge-important { background: #fff9c4; color: #f57f17; }
            .badge-completed { background: #c8e6c9; color: #2e7d32; }
    
            /* SoF Table */
            .sof-table { width: 100%; border-collapse: collapse; font-size: 0.88em; margin-top: 15px; }
            .sof-table th, .sof-table td { border: 1px solid #ccc; padding: 8px; text-align: left; vertical-align: top; }
            .sof-table th { background: var(--primary); color: white; font-weight: bold; }
            .sof-table tr:nth-child(even) { background: #fafafa; }
            
            .sof-input-container { display: flex; gap: 5px; align-items: center; }
            .sof-input-label { font-size: 0.75em; color: #666; margin-right: 2px; }
            .sof-input-md { width: 80px !important; padding: 4px; }
            .sof-input-sm { width: 60px !important; padding: 4px; }
            
            /* SoF Select */
            .sof-select {
                padding: 4px; border-radius: 4px; border: 1px solid #ccc; width: 100%;
                font-weight: bold; font-size: 0.9em;
            }
            .sel-high { color: #2e7d32; }
            .sel-mod { color: #f57f17; }
            .sel-low { color: #c62828; }
            .sel-very-low { color: #757575; }
    
            /* Visualization */
            .viz-wrapper { background: #fcfcfc; padding: 20px; border: 1px solid #eee; border-radius: 8px; text-align: center; margin-top: 20px; }
            canvas { background: white; border: 1px solid #ddd; max-width: 100%; border-radius: 4px; display: block; margin: 15px auto; }
            .result-box { padding: 12px 15px; border-radius: 5px; font-weight: bold; margin-top: 12px; }
            .res-safe { background: #e8f5e9; color: #2e7d32; }
            .res-warn { background: #fff3e0; color: #e65100; }
    
            /* EtD Sections */
            .etd-main-section { 
                border-left: 5px solid var(--primary); background: #f4f8fb; 
                padding: 15px; margin-bottom: 25px; border-radius: 0 8px 8px 0; 
            }
            .etd-option-section { 
                border-left: 5px solid var(--warning); background: #fff8e1; 
                padding: 15px; margin-bottom: 25px; border-radius: 0 8px 8px 0; 
            }
            .etd-title { font-weight: bold; color: #37474f; font-size: 1.1em; margin-bottom: 10px; display: flex; align-items: center; }
            .etd-title span { margin-right: 10px; font-size: 1.2em; }
    
            /* Close Call */
            .close-call-section { background: #fff8e1; border: 2px dashed var(--warning); border-radius: 10px; padding: 20px; margin: 20px 0; }
            .close-call-item { background: white; border: 1px solid #ffcc80; border-radius: 6px; padding: 15px; margin-bottom: 15px; }
    
            @media (max-width: 1000px) {
                .app-container { grid-template-columns: 1fr; }
                .sidebar { display: none; }
                .main-content { padding: 20px; }
                .form-grid-6 { grid-template-columns: repeat(3, 1fr); }
            }
        </style>
    </head>
    <body>
    
    <div class="app-container">
        <nav class="sidebar">
            <div class="logo-area">
                <h1 class="logo-title">Core GRADE Master</h1>
                <div class="logo-sub">v20.1 - Enhanced Explanations</div>
            </div>
            <div class="nav-list">
                <div class="nav-group-title">セットアップ</div>
                <div class="nav-item active" data-nav="pico"><span class="nav-icon">1️⃣</span> PICO設定</div>
                <div class="nav-item" data-nav="outcomes"><span class="nav-icon">2️⃣</span> アウトカム登録</div>
                
                <div class="nav-group-title">5ドメイン評価</div>
                <div class="nav-item" data-nav="rob"><span class="nav-icon">🔍</span> Risk of Bias</div>
                <div class="nav-item" data-nav="inconsistency"><span class="nav-icon">📊</span> Inconsistency</div>
                <div class="nav-item" data-nav="indirectness"><span class="nav-icon">🎯</span> Indirectness</div>
                <div class="nav-item" data-nav="imprecision"><span class="nav-icon">📏</span> Imprecision</div>
                <div class="nav-item" data-nav="pubbias"><span class="nav-icon">📚</span> Publication Bias</div>
                
                <div class="nav-group-title">出力・意思決定</div>
                <div class="nav-item" data-nav="sof"><span class="nav-icon">📋</span> SoFテーブル <span class="nav-badge">入力</span></div>
                <div class="nav-item" data-nav="closecall"><span class="nav-icon">⚖️</span> Close Call記録</div>
                <div class="nav-item" data-nav="etd"><span class="nav-icon">📝</span> EtD・推奨</div>
            </div>
        </nav>
    
        <main class="main-content">
            
            <div id="page-pico" class="section active">
                <h2>Step 1: PICO と研究デザイン設定</h2>
                
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: 確実性の開始点と連続性</summary>
                    <div class="deep-content">
                        <p>エビデンスの確実性は、研究デザインによって開始点が異なります。</p>
                        <div class="guyatt-box">
                            <strong>🎓 ガイアット先生の講演から:</strong><br>
                            「ランダム化比較試験は高い確実性のエビデンスとしてスタートしますが、高い確実性のエビデンスとして終わるとは限りません。<br>
                            非ランダム化介入研究(観察研究)は低い確実性のエビデンスとしてスタートし、さらに格下げされる可能性があります。」
                        </div>
                        <h5>開始点の決定</h5>
                        <ul>
                            <li><strong>High (⊕⊕⊕⊕) スタート:</strong> RCT</li>
                            <li><strong>Low (⊕⊕◯◯) スタート:</strong> 観察研究 (NRSI)</li>
                        </ul>
                        <h5>確実性は連続体である</h5>
                        <p>Core GRADE unpackedが強調するように、確実性は4カテゴリーですが、実際には連続的なスペクトラムです。</p>
                        <div class="info-box">
                            <strong>💡 Close Call(際どい判断):</strong><br>
                            しきい値に近い「際どい判断」は、透明性確保のために明確に記録する必要があります。
                        </div>
                    </div>
                </details>
                
                <div class="card">
                    <h4>PICOフレームワーク</h4>
                    <div class="form-grid">
                        <div><label>Population (対象集団)</label><input type="text" id="pico_p" placeholder="例: 重症敗血症の成人患者"></div>
                        <div><label>Intervention (介入)</label><input type="text" id="pico_i" placeholder="例: 新規抗菌薬A"></div>
                        <div><label>Comparator (比較対照)</label><input type="text" id="pico_c" placeholder="例: 標準治療"></div>
                        <div>
                            <label>Study Design</label>
                            <select id="study_design">
                                <option value="RCT">RCT → High start</option>
                                <option value="OBS">観察研究 → Low start</option>
                            </select>
                        </div>
                    </div>
                </div>
                <button class="btn" id="btn-pico-next">次へ →</button>
            </div>
    
            <div id="page-outcomes" class="section">
                <h2>Step 2: アウトカムの登録と重要度評価</h2>
                
                <details class="deep-dive">
                    <summary>Core GRADE解説: アウトカムの重要度 (1-9点)</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>🎓 ガイアット先生の講演から:</strong><br>
                            「重大(Critical)および重要(Important)なアウトカムを取得します。それほど重要ではない他のアウトカムにはあまり注意を払いません。」
                        </div>
                        <h5>重要度スケール</h5>
                        <ul>
                            <li><strong>7-9: Critical(重大)</strong> - 必須(死亡、心筋梗塞など)</li>
                            <li><strong>4-6: Important(重要)</strong> - SoFに含める(QOL、入院期間など)</li>
                            <li><strong>1-3: Limited</strong> - 通常は除外</li>
                        </ul>
                        <div class="pitfall" style="margin-top:15px; border-color:#d32f2f;">
                            <strong>⚠️ 免責事項:</strong><br>
                            本アプリは、解説と評価のアシストをするものであり、アウトカムごと評価できません。
                        </div>
                    </div>
                </details>
                
                <div class="card">
                    <h4>新規アウトカム追加</h4>
                    <div class="form-grid">
                        <div><label>アウトカム名</label><input type="text" id="new_outcome_name" placeholder="例: 28日死亡率"></div>
                        <div>
                            <label>重要度 (1-9)</label>
                            <select id="new_outcome_imp">
                                <option value="9">9: Critical</option>
                                <option value="8">8: Critical</option>
                                <option value="7">7: Critical</option>
                                <option value="6">6: Important</option>
                                <option value="5">5: Important</option>
                                <option value="4">4: Important</option>
                                <option value="3">3: Limited</option>
                            </select>
                        </div>
                        <div>
                            <label>種類</label>
                            <select id="new_outcome_type">
                                <option value="binary">二値(イベント有無)</option>
                                <option value="continuous">連続(平均値)</option>
                            </select>
                        </div>
                    </div>
                    <button class="btn btn-outline" style="margin-top:12px;" id="btn-add-outcome">+ 追加</button>
                </div>
                
                <h4>登録済みアウトカム</h4>
                <div id="outcome-list"><p style="color:#888;">アウトカムを追加してください。</p></div>
                <div class="btn-group">
                    <button class="btn" id="btn-start-domain">ドメイン評価開始 →</button>
                </div>
            </div>
    
            <div id="page-rob" class="section">
                <h2>Domain 1: バイアスリスク (Risk of Bias)</h2>
                <div class="card card-info"><strong>評価中:</strong> <span id="current_outcome_rob">-</span></div>
    
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: ROBUST-RCT と感度分析アルゴリズム</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>🎓 ガイアット先生の講演から:</strong><br>
                            [cite_start]「Core GRADEの革新は、2つのステップ(何が起こったか→リスク判定)とアルゴリズム的アプローチです。高リスク研究の存在だけで即座にダウンさせるのではなく、全体の重みや感度分析を通じて判断します。」[cite: 2515-2517]
                        </div>
                        
                        [cite_start]<h5>Core GRADE Unpacked (2026) アルゴリズムによる判定フロー [cite: 2562-2583]</h5>
                        <p>このフローチャートは、エビデンス全体としてのバイアスリスクを評価するための手順です。</p>
    
                        <div class="flow-step">
                            <div class="flow-num">1</div>
                            <div>
                                <strong>高リスク研究が支配的か?</strong><br>
                                メタアナリシスにおける重み(Weight)を確認します。<br>
                                ・高リスク研究の重みが <strong>>65%</strong>(または≥55%)を占める場合 → <strong>Yes(支配的)</strong><br>
                                ・そうでない場合 → <strong>No</strong>
                            </div>
                        </div>
    
                        <div class="flow-step">
                            <div class="flow-num">2</div>
                            <div>
                                <strong>(Step 1がYesの場合) バイアスの方向性を確認する</strong><br>
                                バイアスの性質が結果にどう影響するかを考慮します。<br>
                                ・バイアスが「見かけの効果」の原因となっている(過大評価)、または「効果なし」の原因となっている可能性がある場合 → <strong>全研究を使用し、グレードダウンする (-1)</strong><br>
                                ・バイアスが効果を「過小評価(マスク)」している方向の場合(例:プラセボ効果が逆方向に働くなど) → <strong>全研究を使用し、グレードダウンしない (0)</strong>
                            </div>
                        </div>
    
                        <div class="flow-step">
                            <div class="flow-num">3</div>
                            <div>
                                <strong>(Step 1がNoの場合) 低リスク研究の十分なエビデンスがあるか?</strong><br>
                                低リスク研究の重みが <strong>>35-45%</strong> あるかを確認します。<br>
                                ・十分にある場合 → Step 4へ<br>
                                ・不十分な場合 → 全体的に高リスクとみなしグレードダウンを検討
                            </div>
                        </div>
    
                        <div class="flow-step">
                            <div class="flow-num">4</div>
                            <div>
                                <strong>高リスク研究と低リスク研究の結果に実質的な差があるか?</strong><br>
                                感度分析(Sensitivity Analysis)を行います。<br>
                                ・<strong>Yes (差がある)</strong>: 高リスク研究が結果を歪めている可能性があるため、<strong>低リスク研究のみを使用し、グレードダウンしない (0)</strong>。<br>
                                ・<strong>No (差がない)</strong>: 結果は堅牢(Robust)であるため、<strong>全研究を使用し、グレードダウンしない (0)</strong>。<br>
                                <span style="font-size:0.85em; color:#666;">※Core GRADEの革新点: 「高リスク研究が含まれている=即座にダウン」ではなく、感度分析で結果が変わらなければ信頼できると判断します。</span>
                            </div>
                        </div>
                        
                        <div class="pitfall"><strong>注意:</strong> 以前のGRADEでは高リスク研究が含まれるだけでダウンさせることがありましたが、Core GRADEでは「高リスク研究が結果を支配しているか」「感度分析で結果が変わるか」を重視します。</div>
                    </div>
                </details>
                
                <div class="card">
                    <label>バイアスリスク評価</label>
                    <select id="assess_rob">
                        <option value="0">0: Not serious</option>
                        <option value="-1">-1: Serious</option>
                        <option value="-2">-2: Very serious</option>
                    </select>
                    <label style="margin-top:12px;">根拠メモ</label>
                    <textarea id="note_rob"></textarea>
                </div>
                <button class="btn" id="btn-to-inconsistency">次へ: 非一貫性 →</button>
            </div>
    
            <div id="page-inconsistency" class="section">
                <h2>Domain 2: 非一貫性 (Inconsistency)</h2>
                <div class="card card-info"><strong>評価中:</strong> <span id="current_outcome_inconsistency">-</span></div>
    
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: I²の解釈と3ステップ評価</summary>
                    <div class="deep-content">
                        <div class="pitfall"><strong>警告:</strong> I²の数値(例:>50%)だけで機械的にグレードダウンしてはいけません。</div>
                        <h5>評価の3ステップ</h5>
                        <ol>
                            <li><strong>視覚的評価:</strong> 信頼区間(CI)が重なっているか?</li>
                            <li><strong>効果の方向性:</strong> 全て同じ方向(益/害)を示しているか?</li>
                            <li><strong>閾値との関係:</strong> 全ての研究が閾値(Null/MID)の同じ側にあるか?</li>
                        </ol>
                    </div>
                </details>
                
                <div class="card">
                    <label>非一貫性評価</label>
                    <select id="assess_inconsistency">
                        <option value="0">0: Not serious</option>
                        <option value="-1">-1: Serious</option>
                        <option value="-2">-2: Very serious</option>
                    </select>
                    <label style="margin-top:12px;">根拠メモ</label>
                    <textarea id="note_inconsistency"></textarea>
                </div>
                <button class="btn" id="btn-to-indirectness">次へ: 非直接性 →</button>
            </div>
    
            <div id="page-indirectness" class="section">
                <h2>Domain 3: 非直接性 (Indirectness)</h2>
                <div class="card card-info"><strong>評価中:</strong> <span id="current_outcome_indirectness">-</span></div>
    
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: PICOの乖離とサロゲート</summary>
                    <div class="deep-content">
                        <p>エビデンスのPICOと臨床的問い(Target PICO)の乖離を評価します。</p>
                        <div class="pitfall"><strong>サロゲートアウトカム:</strong> 代用エンドポイント(血圧等)が真のアウトカム(死亡等)と強く関連していない場合、-2のグレードダウンが必要です。</div>
                    </div>
                </details>
                
                <div class="card">
                    <label>非直接性評価</label>
                    <select id="assess_indirectness">
                        <option value="0">0: Not serious</option>
                        <option value="-1">-1: Serious</option>
                        <option value="-2">-2: Very serious</option>
                    </select>
                    <label style="margin-top:12px;">根拠メモ</label>
                    <textarea id="note_indirectness"></textarea>
                </div>
                <button class="btn" id="btn-to-imprecision">次へ: 不精確さ →</button>
            </div>
    
            <div id="page-imprecision" class="section">
                <h2>Domain 4: 不精確さ (Imprecision)</h2>
                <div class="card card-info"><strong>評価中:</strong> <span id="current_outcome_imprecision">-</span></div>
    
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: 閾値・OIS・CI比の完全ガイド</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>🎓 ガイアット先生の講演から:</strong><br>
                            [cite_start]「確実性の評価のターゲットについて何が重要かを決める必要があります。閾値(NullまたはMID)を選び、信頼区間がそれを交差するか確認します。交差すれば格下げ、しなければしません。」[cite: 2797-2801]
                        </div>
                        
                        [cite_start]<h5>Core GRADE 2 (2025) 不精確さ判定詳細フロー [cite: 2944-2976]</h5>
                        <p>不精確さは以下のアルゴリズムに従って判定します。</p>
    
                        <div class="flow-step">
                            <div class="flow-num">1</div>
                            <div>
                                <strong>CIは閾値 (Null/MID) をまたぐか?</strong><br>
                                設定した閾値(帰無仮説の値 または 臨床的に重要な最小差 MID)を95%信頼区間が横断しているか確認します。<br>
                                ・<strong>Yes (またぐ)</strong>: 基本的に <strong>グレードダウン (-1)</strong>。<br>
                                [cite_start]<span style="font-size:0.85em; color:#d32f2f;">※さらに「益のMID」と「害のMID」の両方をまたぐ場合、またはPlain Language Summaryで「〜かもしれない (may)」と表現すべきほど不確実な場合は <strong>(-2)</strong> を検討します。[cite: 2951-2956]</span><br>
                                ・<strong>No (またがない)</strong>: Step 2へ。
                            </div>
                        </div>
    
                        <div class="flow-step">
                            <div class="flow-num">2</div>
                            <div>
                                <strong>効果が大きくても、OIS (最適情報サイズ) は満たしているか?</strong><br>
                                CIが閾値をまたがない場合でも、イベント数やサンプルサイズが極端に少なくないか確認します。<br>
                                ・<strong>OISを満たす</strong>(二値変数なら総イベント数 > 300程度、連続変数なら総N > 400-800程度) → <strong>グレードダウンなし (0)</strong>。<br>
                                [cite_start]・<strong>OISを満たさない</strong> → Step 3へ。[cite: 2958-2964]
                            </div>
                        </div>
    
                        <div class="flow-step">
                            <div class="flow-num">3</div>
                            <div>
                                <strong>(OIS未達時) CI比 (CI Ratio) は十分狭いか?</strong><br>
                                OISを満たしていなくても、信頼区間が十分に狭ければ許容されます。<br>
                                ・<strong>二値アウトカム</strong>:<br>
                                 - 相対リスク(RR)のCI比(上限÷下限) < 3、またはオッズ比(OR)のCI比 < 2.5 → <strong>グレードダウンなし (0)</strong>。<br>
                                [cite_start] - RR比 ≧ 3 または OR比 ≧ 2.5 → <strong>グレードダウン (-1〜-2)</strong>。[cite: 2967-2970]<br>
                                ・<strong>連続アウトカム</strong>:<br>
                                [cite_start] - サンプルサイズがOIS(または800)より小さい → <strong>グレードダウン (-1)</strong>。[cite: 2961-2965]
                            </div>
                        </div>
                    </div>
                </details>
    
                <div class="card card-highlight">
                    <h4>🧮 自動判定ツール & Visualizer</h4>
                    
                    <div style="background:#e3f2fd; padding:10px; border-radius:5px; margin-bottom:15px; border:1px solid #90caf9;">
                        <label style="color:#005a9c;">▼ 評価対象のアウトカムを選択</label>
                        <select id="imp_outcome_selector" style="width:100%; font-weight:bold; font-size:1.05em; border:2px solid #005a9c; padding:8px;">
                            </select>
                    </div>
                    
                    <div class="form-grid form-grid-6">
                        <div><label>CI下限 (RR)</label><input type="number" id="imp_low" step="0.01" placeholder="0.65"></div>
                        <div><label>CI上限 (RR)</label><input type="number" id="imp_high" step="0.01" placeholder="0.92"></div>
                        <div><label>点推定値 (RR)</label><input type="number" id="imp_pe" step="0.01" placeholder="0.78"></div>
                        <div><label>イベント数 (計)</label><input type="number" id="imp_events" placeholder="250"></div>
                        <div><label>Base Risk %</label><input type="number" id="imp_base" placeholder="15"></div>
                        <div><label>MID (絶対差/1000)</label><input type="number" id="imp_mid" placeholder="20"></div>
                    </div>
                    
                    <div id="imp_result" class="result-box" style="margin-top:12px;"></div>
    
                    <div class="viz-wrapper">
                        <h5>📊 1000人あたりの絶対効果 (Absolute Risk)</h5>
                        <canvas id="viz_absolute" width="500" height="150"></canvas>
                        
                        <h5 style="margin-top:30px;">📉 MID判定図 (絶対差/1000)</h5>
                        <p style="font-size:0.8em; color:#666;">Core GRADE 2: 信頼区間(CI)がNullまたはMIDをまたぐか確認</p>
                        <canvas id="viz_mid" width="500" height="120"></canvas>
                    </div>
                </div>
    
                <div class="card">
                    <label>不精確さ評価</label>
                    <select id="assess_imprecision">
                        <option value="0">0: Not serious</option>
                        <option value="-1">-1: Serious</option>
                        <option value="-2">-2: Very serious</option>
                    </select>
                    <label style="margin-top:12px;">根拠メモ</label>
                    <textarea id="note_imprecision"></textarea>
                </div>
                <button class="btn" id="btn-to-pubbias">次へ: 出版バイアス →</button>
            </div>
    
            <div id="page-pubbias" class="section">
                <h2>Domain 5: 出版バイアス (Publication Bias)</h2>
                <div class="card card-info"><strong>評価中:</strong> <span id="current_outcome_pubbias">-</span></div>
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: 小規模研究効果と選択的報告</summary>
                    <div class="deep-content">
                        <div class="pitfall"><strong>区別:</strong> 出版バイアス(研究ごとの未発表)と選択的報告(RoBドメイン:解析結果の選別)を混同しないようにしてください。</div>
                        <p>小規模研究効果(小さい研究ほど効果が大きい)がある場合、出版バイアスを疑います。</p>
                    </div>
                </details>
                <div class="card">
                    <label>出版バイアス評価</label>
                    <select id="assess_pubbias">
                        <option value="0">0: Undetected</option>
                        <option value="-1">-1: Strongly suspected</option>
                    </select>
                    <label style="margin-top:12px;">根拠メモ</label>
                    <textarea id="note_pubbias"></textarea>
                </div>
                <div class="btn-group">
                    <button class="btn btn-success" id="btn-finish-outcome">✓ このアウトカム評価完了</button>
                </div>
            </div>
    
            <div id="page-sof" class="section">
                <h2>Summary of Findings (SoF) テーブル</h2>
                <details class="deep-dive">
                    <summary>Core GRADE解説: SoFテーブルの構成</summary>
                    <div class="deep-content">
                        <p>SoFテーブルはエビデンスの要約です。絶対効果(1000人あたりの差)が最も重要です。</p>
                        <p>絶対リスク差 (ARD) = Baseline Risk × (RR - 1) × 1000</p>
                    </div>
                </details>
                
                <div class="card">
                    <h4>PICO</h4>
                    <p id="sof_pico_display">-</p>
                </div>
                
                <div class="card card-highlight">
                    <h4>📋 SoFテーブル(全データ入力・編集)</h4>
                    <p style="font-size:0.85em; color:#666;">
                        95%信頼区間、確実性、MIDなどを直接編集できます。入力データはEtDセクションの統合グラフに即座に反映されます。
                    </p>
                    <div style="overflow-x:auto;">
                        <table class="sof-table">
                            <thead>
                                <tr>
                                    <th style="min-width:150px;">アウトカム & 重要度</th>
                                    <th style="min-width:90px;">参加者数</th>
                                    <th style="min-width:220px;">相対効果 (RR & 95%CI)</th>
                                    <th style="min-width:100px;">絶対効果 (/1000)</th>
                                    <th style="min-width:80px;">MID</th>
                                    <th style="min-width:130px;">確実性 (Manual)</th>
                                    <th style="min-width:180px;">Plain Language</th>
                                </tr>
                            </thead>
                            <tbody id="sof_tbody"></tbody>
                        </table>
                    </div>
                </div>
                <div class="btn-group">
                    <button class="btn" id="btn-refresh-sof">テーブル更新(再計算)</button>
                    <button class="btn btn-outline" id="btn-to-closecall">Close Call記録へ →</button>
                </div>
            </div>
    
            <div id="page-closecall" class="section">
                <h2>Close Call(際どい判断)</h2>
                <details class="deep-dive" open>
                    <summary>Core GRADE解説: 境界領域での判断</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>🎓 ガイアット先生の講演から:</strong><br>
                            「確実性は連続体です。しきい値に近い場合(例:ModerateとLowの境界)、その判断根拠を透明にする必要があります。」
                        </div>
                    </div>
                </details>
                
                <div class="close-call-section">
                    <h4>⚖️ 確実性 / 推奨の強さに関するClose Call</h4>
                    <div class="close-call-item">
                        <label>アウトカム選択</label>
                        <select id="cc_certainty_outcome" style="margin-bottom:10px;"></select>
                        <label>判断内容</label>
                        <textarea id="cc_certainty_rationale" placeholder="例:RoBは境界域だが、全研究が同方向のためダウンしないと判断。"></textarea>
                        <button class="btn btn-sm btn-outline" id="btn-add-certainty-cc" style="margin-top:10px;">+ 記録追加</button>
                    </div>
                    <div id="certainty-closecall-list"></div>
                </div>
                <div class="btn-group">
                    <button class="btn" id="btn-to-etd">EtD・推奨作成へ →</button>
                </div>
            </div>
    
            <div id="page-etd" class="section">
                <h2>Evidence to Decision (EtD) & 推奨作成</h2>
                <details class="deep-dive">
                    <summary>Core GRADE解説: EtDフレームワーク (Core GRADE 7)</summary>
                    <div class="deep-content">
                        <p>推奨決定には、以下の要因を体系的に検討します。</p>
                        <ul>
                            <li><strong>Main (主要基準):</strong> 益と害のバランス、確実性、価値観。これらは臨床現場・個人レベルで必須です。</li>
                            <li><strong>Contextual/Additional (その他の考慮事項):</strong> コスト、公平性、受容性、実行可能性。これらは公衆衛生・政策決定で重要です。</li>
                        </ul>
                    </div>
                </details>
                
                <div class="card">
                    <h4>📊 1. 全アウトカム統合フォレストプロット (Effect & Certainty)</h4>
                    <div class="viz-wrapper" style="border:1px solid #90caf9; background:#e3f2fd;">
                        <p style="font-size:0.8em; color:#333;">SoFで入力された全アウトカム(重要度4以上)の絶対効果、MID、確実性を一覧表示します。</p>
                        <canvas id="viz_etd_forest" width="750" height="400"></canvas>
                    </div>
    
                    <h4>2. 主要な基準 (Main Criteria)</h4>
                    <div class="etd-main-section">
                        <div class="etd-title"><span>⚖️</span> 問題の優先度 & 益と害のバランス</div>
                        <div class="form-grid-2">
                            <div class="outcome-card">
                                <div><strong>問題の優先度</strong><br><span style="font-size:0.8em; color:#666;">Is the problem a priority?</span></div>
                                <select class="sof-input-md"><option value="yes">Yes</option><option value="no">No</option><option value="uncertain">Varies</option></select>
                            </div>
                            <div class="outcome-card" id="etd_balance">
                                <div><strong>益と害のバランス</strong><br><span style="font-size:0.8em; color:#666;">絶対効果の差に基づく</span></div>
                                <select class="sof-input-md"><option value="neutral">同等/不明</option><option value="favors_i">介入有利</option><option value="favors_c">対照有利</option></select>
                            </div>
                        </div>
    
                        <div class="etd-title"><span>🔍</span> エビデンスの確実性 & 価値観</div>
                        <div class="form-grid-2">
                            <div class="outcome-card" id="etd_certainty">
                                <div><strong>全体的な確実性</strong><br><span style="font-size:0.8em; color:#666;">全アウトカムの最低値</span></div>
                                <select class="sof-input-md"><option value="low">Low</option><option value="high">High</option><option value="moderate">Moderate</option><option value="very_low">Very Low</option></select>
                            </div>
                            <div class="outcome-card">
                                <div><strong>価値観のばらつき</strong><br><span style="font-size:0.8em; color:#666;">Values & Preferences</span></div>
                                <select class="sof-input-md"><option value="no_var">ばらつき小</option><option value="var">ばらつき大</option><option value="uncertain">不明</option></select>
                            </div>
                        </div>
                    </div>
    
                    <h4>3. その他の考慮事項 (Contextual / Additional Criteria)</h4>
                    <div class="etd-option-section">
                        <div class="etd-title"><span>💰</span> 資源・コスト (Resources)</div>
                        <div class="form-grid-3">
                            <div class="outcome-card">
                                <div><strong>必要な資源</strong><br><span style="font-size:0.8em; color:#666;">Resources required</span></div>
                                <select class="sof-input-md"><option value="negligible">無視できる</option><option value="moderate">中程度</option><option value="large">大きい</option></select>
                            </div>
                            <div class="outcome-card">
                                <div><strong>資源の確実性</strong><br><span style="font-size:0.8em; color:#666;">Certainty of resources</span></div>
                                <select class="sof-input-md"><option value="high">High</option><option value="low">Low</option></select>
                            </div>
                            <div class="outcome-card">
                                <div><strong>費用対効果</strong><br><span style="font-size:0.8em; color:#666;">Cost effectiveness</span></div>
                                <select class="sof-input-md"><option value="favors_i">介入有利</option><option value="favors_c">対照有利</option><option value="neutral">不明</option></select>
                            </div>
                        </div>
    
                        <div class="etd-title"><span>🌍</span> 公平性・受容性・実行可能性</div>
                        <div class="form-grid-3">
                            <div class="outcome-card">
                                <div><strong>公平性 (Equity)</strong><br><span style="font-size:0.8em; color:#666;">Impact on equity</span></div>
                                <select class="sof-input-md"><option value="neutral">影響なし</option><option value="reduced">格差縮小</option><option value="increased">格差拡大</option></select>
                            </div>
                            <div class="outcome-card">
                                <div><strong>受容性 (Acceptability)</strong><br><span style="font-size:0.8em; color:#666;">Is it acceptable?</span></div>
                                <select class="sof-input-md"><option value="yes">Yes</option><option value="no">No</option><option value="uncertain">Uncertain</option></select>
                            </div>
                            <div class="outcome-card">
                                <div><strong>実行可能性 (Feasibility)</strong><br><span style="font-size:0.8em; color:#666;">Is it feasible?</span></div>
                                <select class="sof-input-md"><option value="yes">Yes</option><option value="no">No</option><option value="uncertain">Uncertain</option></select>
                            </div>
                        </div>
                    </div>
                    
                    <h4 style="margin-top:25px;">最終推奨 (Recommendation)</h4>
                    <div class="form-grid">
                        <button class="outcome-card" onclick="selectRec(this, 'strong_for')"><span style="color:#2e7d32; font-weight:bold;">Strong FOR</span><br><span style="font-size:0.8em;">強く推奨</span></button>
                        <button class="outcome-card" onclick="selectRec(this, 'cond_for')"><span style="color:#43a047; font-weight:bold;">Conditional FOR</span><br><span style="font-size:0.8em;">条件付き推奨</span></button>
                        <button class="outcome-card" onclick="selectRec(this, 'cond_against')"><span style="color:#e65100; font-weight:bold;">Conditional AGAINST</span><br><span style="font-size:0.8em;">条件付き非推奨</span></button>
                        <button class="outcome-card" onclick="selectRec(this, 'strong_against')"><span style="color:#c62828; font-weight:bold;">Strong AGAINST</span><br><span style="font-size:0.8em;">強く非推奨</span></button>
                    </div>
                    
                    <label style="margin-top:15px;">推奨文ドラフト</label>
                    <textarea id="rec_text"></textarea>
                    <label style="margin-top:15px;">正当性 (Justification)</label>
                    <textarea id="rec_justification" placeholder="推奨の理由を記述してください..."></textarea>
                </div>
                <div class="btn-group">
                    <button class="btn btn-outline" onclick="window.print()">🖨️ レポート保存</button>
                </div>
            </div>
    
        </main>
    </div>
    
    <script>
        // --- Data Store (Single Source of Truth) ---
        const appData = {
            pico: { p: '', i: '', c: '', design: 'RCT' },
            outcomes: [], 
            // outcomes structure: { id, name, imp, rr, ci_low, ci_high, abs_diff, mid, base_risk, ... assessments ..., certainty_override: null }
            currentOutcomeId: null,
            closeCalls: [],
            etd: { recommendation: '' }
        };
    
        // --- Navigation ---
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', () => {
                document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
                item.classList.add('active');
                document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
                document.getElementById('page-' + item.dataset.nav).classList.add('active');
                
                // Refresh specific sections on tab switch
                if (item.dataset.nav === 'sof') renderSoF();
                if (item.dataset.nav === 'etd') updateEtD();
            });
        });
    
        // --- PICO ---
        document.getElementById('btn-pico-next').addEventListener('click', () => {
            appData.pico.p = document.getElementById('pico_p').value;
            appData.pico.i = document.getElementById('pico_i').value;
            appData.pico.c = document.getElementById('pico_c').value;
            appData.pico.design = document.getElementById('study_design').value;
            document.querySelector('[data-nav="outcomes"]').click();
        });
    
        // --- Outcomes ---
        document.getElementById('btn-add-outcome').addEventListener('click', () => {
            const name = document.getElementById('new_outcome_name').value;
            if (!name) return alert('アウトカム名を入力してください');
            
            const outcome = {
                id: Date.now().toString(),
                name: name,
                imp: parseInt(document.getElementById('new_outcome_imp').value),
                type: document.getElementById('new_outcome_type').value,
                // Assessments
                rob: 0, rob_note: '', inconsistency: 0, inconsistency_note: '',
                indirectness: 0, indirectness_note: '', imprecision: 0, imprecision_note: '',
                pubbias: 0, pubbias_note: '',
                // Values for Calc/SoF
                rr: 1.0, ci_low: 0.8, ci_high: 1.2, // Defaults
                n_events: 0, base_risk: 15, mid: 20, abs_diff: 0,
                n_participants: 0,
                certainty_override: null // For manual change in SoF
            };
            appData.outcomes.push(outcome);
            renderOutcomeList();
            updateAllOutcomeSelectors(); 
            document.getElementById('new_outcome_name').value = '';
        });
    
        function renderOutcomeList() {
            const list = document.getElementById('outcome-list');
            list.innerHTML = '';
            appData.outcomes.forEach(o => {
                const div = document.createElement('div');
                div.className = 'outcome-card';
                let badgeClass = o.imp >= 7 ? 'badge-critical' : (o.imp >=4 ? 'badge-important' : 'badge-completed');
                div.innerHTML = `<div><strong>${o.name}</strong></div><div class="outcome-badge ${badgeClass}">${o.imp}</div>`;
                div.addEventListener('click', () => selectOutcome(o.id));
                list.appendChild(div);
            });
        }
    
        // Centralized Outcome Selector Updater
        function updateAllOutcomeSelectors() {
            const selectors = [
                document.getElementById('imp_outcome_selector'),
                document.getElementById('cc_certainty_outcome')
            ];
            
            selectors.forEach(sel => {
                if(!sel) return;
                const currentVal = sel.value; 
                sel.innerHTML = '<option value="">-- 選択 --</option>';
                appData.outcomes.forEach(o => {
                    const opt = document.createElement('option');
                    opt.value = o.id;
                    opt.text = o.name + (o.imp >= 7 ? ' (Critical)' : '');
                    sel.appendChild(opt);
                });
                if(currentVal) sel.value = currentVal;
            });
        }
    
        // --- Selection Logic ---
        function selectOutcome(id) {
            appData.currentOutcomeId = id;
            const o = appData.outcomes.find(x => x.id === id);
            
            // Sync Dropdowns
            document.getElementById('imp_outcome_selector').value = id;
            
            // Update Headers
            ['rob', 'inconsistency', 'indirectness', 'imprecision', 'pubbias'].forEach(dom => {
                const el = document.getElementById('current_outcome_'+dom);
                if(el) el.textContent = o.name;
            });
    
            // Load Domain Data
            ['rob', 'inconsistency', 'indirectness', 'imprecision', 'pubbias'].forEach(dom => {
                document.getElementById('assess_'+dom).value = o[dom];
                document.getElementById('note_'+dom).value = o[dom+'_note'];
            });
    
            // Load Calc Data
            loadCalcDataToInputs(o);
            calcImprecision(); // Draw immediately
        }
    
        function loadCalcDataToInputs(o) {
            document.getElementById('imp_low').value = o.ci_low || '';
            document.getElementById('imp_high').value = o.ci_high || '';
            document.getElementById('imp_pe').value = o.rr || '';
            document.getElementById('imp_events').value = o.n_events || '';
            document.getElementById('imp_base').value = o.base_risk || '';
            document.getElementById('imp_mid').value = o.mid || '';
        }
    
        // Sync Imprecision Selector
        document.getElementById('imp_outcome_selector').addEventListener('change', (e) => {
            if(e.target.value) selectOutcome(e.target.value);
        });
    
        // Domain Navigation Buttons
        document.getElementById('btn-start-domain').addEventListener('click', () => {
            if(!appData.outcomes.length) return alert('アウトカム登録が必要です');
            if(!appData.currentOutcomeId) selectOutcome(appData.outcomes[0].id);
            document.querySelector('[data-nav="rob"]').click();
        });
        
        ['rob','inconsistency','indirectness','imprecision','pubbias'].forEach((dom, idx, arr) => {
            const nextBtn = document.querySelector(`#page-${dom} .btn`);
            if(nextBtn && idx < arr.length - 1) {
                nextBtn.addEventListener('click', () => {
                    saveCurrentDomain(dom);
                    document.querySelector(`[data-nav="${arr[idx+1]}"]`).click();
                });
            }
        });
        // Finish button
        document.getElementById('btn-finish-outcome').addEventListener('click', () => {
            saveCurrentDomain('pubbias');
            alert('評価完了');
            document.querySelector('[data-nav="outcomes"]').click();
        });
    
        function saveCurrentDomain(dom) {
            if(!appData.currentOutcomeId) return;
            const o = appData.outcomes.find(x => x.id === appData.currentOutcomeId);
            o[dom] = parseInt(document.getElementById('assess_'+dom).value);
            o[dom+'_note'] = document.getElementById('note_'+dom).value;
        }
    
        // --- Imprecision Calculator & Visualizer ---
        const impInputs = ['imp_low', 'imp_high', 'imp_pe', 'imp_events', 'imp_base', 'imp_mid'];
        impInputs.forEach(id => {
            document.getElementById(id).addEventListener('input', () => {
                if(!appData.currentOutcomeId) return;
                const o = appData.outcomes.find(x => x.id === appData.currentOutcomeId);
                
                // Save immediately
                o.ci_low = parseFloat(document.getElementById('imp_low').value);
                o.ci_high = parseFloat(document.getElementById('imp_high').value);
                o.rr = parseFloat(document.getElementById('imp_pe').value);
                o.n_events = parseInt(document.getElementById('imp_events').value);
                o.base_risk = parseFloat(document.getElementById('imp_base').value);
                o.mid = parseFloat(document.getElementById('imp_mid').value);
                
                if(o.base_risk && o.rr) {
                    o.abs_diff = Math.round(o.base_risk * (o.rr - 1) * 10);
                }
                
                calcImprecision();
            });
        });
    
        function calcImprecision() {
            const o = appData.outcomes.find(x => x.id === appData.currentOutcomeId);
            if(!o) return;
    
            drawViz(o, 'viz_absolute', 'abs');
            drawViz(o, 'viz_mid', 'mid');
    
            const resBox = document.getElementById('imp_result');
            let msg = "";
            let isWarn = false;
            const low = o.ci_low || 1; 
            const high = o.ci_high || 1;
            const events = o.n_events || 0;
    
            if (low < 1.0 && high > 1.0) {
                msg += "⚠️ CIがNull(1.0)をまたぐ (-1)。 ";
                isWarn = true;
            } else {
                msg += "✅ CIはNullをまたがない。 ";
            }
    
            if (events > 0 && events < 300) {
                msg += `⚠️ イベント数 ${events} < 300 (OIS未達)。`;
                isWarn = true;
            } else if (events >= 300) {
                msg += "✅ OIS OK。";
            }
            resBox.textContent = msg;
            resBox.className = "result-box " + (isWarn ? "res-warn" : "res-safe");
        }
    
        function drawViz(o, canvasId, type) {
            const canvas = document.getElementById(canvasId);
            if(!canvas) return;
            const ctx = canvas.getContext('2d');
            const w = canvas.width; 
            const h = canvas.height;
            ctx.clearRect(0, 0, w, h);
    
            const base = o.base_risk || 15;
            const rr = o.rr || 1.0;
            const low = o.ci_low || 1.0;
            const high = o.ci_high || 1.0;
            const mid = o.mid || 20;
    
            if(type === 'abs') {
                const nControl = Math.round(base * 10);
                const nInterv = Math.round(base * rr * 10);
                const scale = (w - 100) / 1000;
    
                ctx.fillStyle = '#90caf9'; ctx.fillRect(50, 30, nControl * scale, 40);
                ctx.fillStyle = '#000'; ctx.fillText(`対照: ${nControl}/1000`, 50, 20);
    
                ctx.fillStyle = '#a5d6a7'; ctx.fillRect(50, 90, nInterv * scale, 40);
                ctx.fillStyle = '#000'; ctx.fillText(`介入: ${nInterv}/1000`, 50, 80);
                
                ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(w-50, 140); ctx.stroke();
                ctx.fillText("0", 50, 150); ctx.fillText("1000人", w-60, 150);
    
            } else if (type === 'mid') {
                const ardPE = base * (rr - 1) * 10;
                const ardLow = base * (low - 1) * 10;
                const ardHigh = base * (high - 1) * 10;
    
                const cx = w / 2;
                const cy = h / 2;
                const maxRange = Math.max(Math.abs(ardLow), Math.abs(ardHigh), mid * 1.5, 50);
                const scale = (w/2 - 40) / maxRange;
    
                ctx.beginPath(); ctx.moveTo(cx, 10); ctx.lineTo(cx, h-10); ctx.strokeStyle='#000'; ctx.stroke();
                ctx.fillText("Null", cx-10, h-5);
    
                ctx.setLineDash([5,5]); ctx.strokeStyle='#d32f2f'; ctx.fillStyle='#d32f2f';
                ctx.beginPath(); 
                ctx.moveTo(cx - mid*scale, 10); ctx.lineTo(cx - mid*scale, h-10); 
                ctx.moveTo(cx + mid*scale, 10); ctx.lineTo(cx + mid*scale, h-10);
                ctx.stroke(); ctx.setLineDash([]);
                ctx.fillText(`-MID`, cx - mid*scale - 15, 20);
                ctx.fillText(`+MID`, cx + mid*scale - 15, 20);
    
                ctx.strokeStyle = '#005a9c'; ctx.lineWidth = 4;
                ctx.beginPath(); ctx.moveTo(cx + ardLow*scale, cy); ctx.lineTo(cx + ardHigh*scale, cy); ctx.stroke();
                
                ctx.fillStyle = '#005a9c';
                ctx.beginPath(); ctx.arc(cx + ardPE*scale, cy, 6, 0, Math.PI*2); ctx.fill();
                
                ctx.fillStyle = '#000'; ctx.lineWidth = 1;
                ctx.fillText(`${ardPE.toFixed(1)}`, cx + ardPE*scale - 10, cy - 15);
            }
        }
    
        // --- SoF Table ---
        function getCertainty(o) {
            if (o.certainty_override) return o.certainty_override; // Manual override
            const start = appData.pico.design === 'RCT' ? 4 : 2;
            let rating = start + o.rob + o.inconsistency + o.indirectness + o.imprecision + o.pubbias;
            if(rating < 1) rating = 1; if(rating > 4) rating = 4;
            return rating;
        }
    
        function renderSoF() {
            const tbody = document.getElementById('sof_tbody');
            tbody.innerHTML = '';
            
            appData.outcomes.forEach(o => {
                if(o.imp < 4) return;
                const tr = document.createElement('tr');
                const rating = getCertainty(o);
                
                const opts = [
                    {v:4, l:'High', c:'sel-high'},
                    {v:3, l:'Moderate', c:'sel-mod'},
                    {v:2, l:'Low', c:'sel-low'},
                    {v:1, l:'Very Low', c:'sel-very-low'}
                ].map(opt => `<option value="${opt.v}" class="${opt.c}" ${rating==opt.v?'selected':''}>${opt.l}</option>`).join('');
    
                // Importance Options
                const impOpts = [9,8,7,6,5,4].map(v => `<option value="${v}" ${o.imp==v?'selected':''}>${v}</option>`).join('');
    
                tr.innerHTML = `
                    <td>
                        <input class="sof-input-md" value="${o.name}" onchange="updateOutcomeData('${o.id}', 'name', this.value)" style="width:100% !important; margin-bottom:5px;">
                        <br>
                        <span class="sof-input-label">Imp:</span>
                        <select class="sof-input-sm" onchange="updateOutcomeData('${o.id}', 'imp', this.value)">${impOpts}</select>
                    </td>
                    <td><input class="sof-input-md" value="${o.n_participants || ''}" onchange="updateOutcomeData('${o.id}', 'n_participants', this.value)"></td>
                    <td>
                        <div class="sof-input-container"><span class="sof-input-label">RR</span><input class="sof-input-sm" value="${o.rr || ''}" onchange="updateOutcomeData('${o.id}', 'rr', this.value)"></div>
                        <div class="sof-input-container"><span class="sof-input-label">Low</span><input class="sof-input-sm" value="${o.ci_low || ''}" onchange="updateOutcomeData('${o.id}', 'ci_low', this.value)"></div>
                        <div class="sof-input-container"><span class="sof-input-label">High</span><input class="sof-input-sm" value="${o.ci_high || ''}" onchange="updateOutcomeData('${o.id}', 'ci_high', this.value)"></div>
                    </td>
                    <td><input class="sof-input-md" value="${o.abs_diff || ''}" onchange="updateOutcomeData('${o.id}', 'abs_diff', this.value)"></td>
                    <td><input class="sof-input-sm" value="${o.mid || ''}" onchange="updateOutcomeData('${o.id}', 'mid', this.value)"></td>
                    <td>
                        <select class="sof-select" onchange="updateOutcomeData('${o.id}', 'certainty_override', this.value)">
                            ${opts}
                        </select>
                    </td>
                    <td>${rating>=3 ? '減らす' : '減らす可能性がある'}</td>
                `;
                tbody.appendChild(tr);
            });
        }
    
        window.updateOutcomeData = function(id, field, val) {
            const o = appData.outcomes.find(x => x.id === id);
            if(o) {
                o[field] = parseFloat(val) || val; // Parse if number
                if(field === 'certainty_override' || field === 'imp') o[field] = parseInt(val);
                if(field === 'name') o[field] = val; // Force string for name
            }
        };
        
        document.getElementById('btn-refresh-sof').addEventListener('click', renderSoF);
    
        // --- EtD: All Outcomes Viz (Forest Plot) ---
        function updateEtD() {
            const canvas = document.getElementById('viz_etd_forest');
            if(!canvas) return;
            const ctx = canvas.getContext('2d');
            const w = canvas.width;
            
            // Filter important outcomes
            const visibleOutcomes = appData.outcomes.filter(o => o.imp >= 4);
            const rowH = 60;
            const headerH = 40;
            canvas.height = headerH + (visibleOutcomes.length * rowH) + 20;
            const h = canvas.height;
    
            ctx.clearRect(0,0,w,h);
            ctx.fillStyle = '#fff'; ctx.fillRect(0,0,w,h); 
    
            // Header Background
            ctx.fillStyle = '#e3f2fd'; ctx.fillRect(0,0,w,headerH);
            
            // Header Text
            ctx.fillStyle = '#000'; ctx.font = 'bold 13px Arial';
            ctx.fillText("Outcome", 10, 25);
            ctx.fillText("Imp", 150, 25);
            ctx.fillText("Cert", 200, 25);
            ctx.fillText("Absolute Effect (/1000) & MID", 380, 25);
    
            // Chart Area setup
            const chartX = 300;
            const chartW = 400;
            const cx = chartX + chartW/2; // Null line
    
            // Find scale range
            let maxRange = 50; 
            visibleOutcomes.forEach(o => {
                const base = o.base_risk || 15;
                // Abs diff from SoF inputs (RR based)
                // ARD = Base * (RR-1) * 10
                const ardLow = base * ((o.ci_low||1) - 1) * 10;
                const ardHigh = base * ((o.ci_high||1) - 1) * 10;
                const mid = o.mid || 20;
                maxRange = Math.max(maxRange, Math.abs(ardLow), Math.abs(ardHigh), mid*1.2);
            });
            const scale = (chartW/2 - 20) / maxRange;
    
            // Draw Rows
            visibleOutcomes.forEach((o, i) => {
                const y = headerH + (i * rowH) + 30;
                
                // 1. Text Columns
                ctx.fillStyle = '#000'; ctx.font = '13px Arial';
                ctx.fillText(o.name, 10, y);
                
                // Imp Badge
                ctx.font = 'bold 12px Arial';
                if(o.imp >=7) { ctx.fillStyle='#c62828'; ctx.fillText(o.imp + " (Crit)", 150, y); }
                else { ctx.fillStyle='#f57f17'; ctx.fillText(o.imp + " (Imp)", 150, y); }
    
                // Cert Badge
                const cert = getCertainty(o);
                const certTxt = ['','VL','Low','Mod','High'][cert];
                const certColor = ['','#757575','#d32f2f','#f57f17','#2e7d32'][cert];
                ctx.fillStyle = certColor;
                ctx.fillText(certTxt, 200, y);
    
                // 2. Graph
                const base = o.base_risk || 15;
                const rr = o.rr || 1.0;
                const low = o.ci_low || 1.0;
                const high = o.ci_high || 1.0;
                const mid = o.mid || 20;
    
                const ardPE = base * (rr - 1) * 10;
                const ardLow = base * (low - 1) * 10;
                const ardHigh = base * (high - 1) * 10;
    
                // Null Line
                ctx.beginPath(); ctx.moveTo(cx, headerH); ctx.lineTo(cx, h); ctx.strokeStyle='#ccc'; ctx.lineWidth=1; ctx.stroke();
    
                // MID Areas (Shaded) or Lines
                // Let's draw MID lines
                ctx.fillStyle='rgba(211, 47, 47, 0.2)'; // Light red
                // Area outside MID? Or Area inside? Usually MID lines are critical.
                // Draw lines
                ctx.strokeStyle='#d32f2f'; ctx.setLineDash([2,2]);
                ctx.beginPath(); ctx.moveTo(cx - mid*scale, headerH); ctx.lineTo(cx - mid*scale, h); ctx.stroke();
                ctx.beginPath(); ctx.moveTo(cx + mid*scale, headerH); ctx.lineTo(cx + mid*scale, h); ctx.stroke();
                ctx.setLineDash([]);
    
                // Effect Line (CI)
                ctx.strokeStyle = '#005a9c'; ctx.lineWidth = 3;
                ctx.beginPath(); ctx.moveTo(cx + ardLow*scale, y-5); ctx.lineTo(cx + ardHigh*scale, y-5); ctx.stroke();
    
                // Point Estimate
                ctx.fillStyle='#005a9c'; 
                ctx.beginPath(); ctx.arc(cx + ardPE*scale, y-5, 5, 0, Math.PI*2); ctx.fill();
    
                // Values Text
                ctx.fillStyle='#666'; ctx.font='10px Arial';
                ctx.fillText(ardPE.toFixed(1), cx + ardPE*scale - 10, y + 15);
            });
        }
    
        // --- Close Call ---
        document.getElementById('btn-add-certainty-cc').addEventListener('click', () => {
            const text = document.getElementById('cc_certainty_rationale').value;
            const oid = document.getElementById('cc_certainty_outcome').value;
            const oName = oid ? appData.outcomes.find(x=>x.id===oid).name : 'General';
            if(!text) return;
            const div = document.createElement('div');
            div.className = 'close-call-item';
            div.innerHTML = `<strong>${oName}</strong>: ${text}`;
            document.getElementById('certainty-closecall-list').appendChild(div);
            document.getElementById('cc_certainty_rationale').value = '';
        });
    
        function selectRec(btn, type) {
            document.querySelectorAll('#page-etd .outcome-card').forEach(b => b.classList.remove('selected'));
            btn.classList.add('selected');
            const map = {
                'strong_for': '強く推奨する', 'cond_for': '条件付きで推奨する',
                'cond_against': '条件付きで推奨しない', 'strong_against': '強く推奨しない'
            };
            document.getElementById('rec_text').value = `${appData.pico.p}に対して、パネルは${appData.pico.i}を${map[type]}。`;
        }
    
    </script>
    </body>
    </html>

    絶対効果フォレストプロット

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Core GRADE Master v23.1: Stable Final</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
        <style>
            :root {
                --primary: #0d47a1;
                --primary-light: #e3f2fd;
                --accent: #d32f2f;
                --text-main: #333;
                --border: #cfd8dc;
                --white: #ffffff;
                --bg-body: #f5f7fa;
            }
    
            * { box-sizing: border-box; }
    
            body {
                font-family: "Helvetica Neue", Arial, sans-serif;
                background-color: var(--bg-body);
                color: var(--text-main);
                margin: 0;
                padding: 0;
                line-height: 1.6;
                height: 100vh;
                display: flex;
                flex-direction: column;
            }
    
            /* Header */
            header {
                background: var(--primary);
                color: white;
                padding: 15px 25px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                z-index: 100;
            }
            .app-title { font-size: 1.4em; font-weight: bold; margin: 0; }
    
            /* Main Layout */
            .container {
                display: flex;
                flex: 1;
                overflow: hidden;
            }
    
            /* Sidebar */
            .sidebar {
                width: 250px;
                background: var(--white);
                border-right: 1px solid var(--border);
                display: flex;
                flex-direction: column;
                padding-top: 10px;
            }
            .nav-item {
                padding: 15px 20px;
                cursor: pointer;
                color: #546e7a;
                font-weight: 600;
                transition: 0.2s;
                display: flex;
                align-items: center;
                border-left: 4px solid transparent;
            }
            .nav-item:hover { background: var(--primary-light); color: var(--primary); }
            .nav-item.active { 
                background: var(--primary-light); 
                color: var(--primary); 
                border-left-color: var(--primary);
            }
            .nav-icon { margin-right: 12px; font-size: 1.2em; }
    
            /* Content Area */
            .content {
                flex: 1;
                padding: 30px 40px;
                overflow-y: auto;
                background: var(--bg-body);
            }
            .page { display: none; animation: fadeIn 0.3s ease; }
            .page.active { display: block; }
            @keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
    
            h2 { border-bottom: 2px solid var(--border); padding-bottom: 10px; color: var(--primary); margin-top: 0; }
            h3 { color: #455a64; margin-top: 25px; font-size: 1.2em; border-left: 4px solid var(--primary); padding-left: 10px; }
    
            /* Cards */
            .card {
                background: var(--white);
                border-radius: 8px;
                padding: 25px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.05);
                margin-bottom: 20px;
                border: 1px solid var(--border);
            }
            .card-highlight { border: 2px solid var(--primary); background: #fdfdfd; }
    
            /* Forms */
            .form-row { display: flex; gap: 20px; margin-bottom: 15px; }
            .form-group { flex: 1; }
            label { display: block; font-weight: bold; margin-bottom: 5px; font-size: 0.9em; color: #546e7a; }
            input, select, textarea {
                width: 100%; padding: 10px; border: 1px solid #b0bec5; border-radius: 4px;
                font-size: 0.95em; transition: border 0.2s;
            }
            input:focus, select:focus, textarea:focus { border-color: var(--primary); outline: none; }
            
            /* SoF Table Styling */
            .sof-container { overflow-x: auto; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
            .sof-table { 
                width: 100%; border-collapse: collapse; background: white; font-size: 0.9em; 
                min-width: 1200px; 
            }
            .sof-table th { background: #37474f; color: white; padding: 12px; text-align: left; white-space: nowrap; }
            .sof-table td { border-bottom: 1px solid #eceff1; padding: 10px; vertical-align: top; }
            .sof-table tr:nth-child(even) { background: #f9fafb; }
            .sof-table input, .sof-table select { padding: 6px; font-size: 0.9em; border: 1px solid #cfd8dc; }
            
            /* Input Sizes */
            .sof-input-container { display: flex; gap: 5px; align-items: center; }
            .sof-input-label { font-size: 0.75em; color: #666; margin-right: 2px; }
            .sof-input-md { width: 80px !important; padding: 4px; }
            .sof-input-sm { width: 60px !important; padding: 4px; }
            .sof-input-xs { width: 50px !important; padding: 4px; }
            
            .calc-value { font-weight: bold; color: #0d47a1; background: #e3f2fd; padding: 5px; border-radius: 4px; display: inline-block; min-width: 60px; text-align: center; }
            .calc-sub { font-size: 0.85em; color: #666; display: block; margin-top: 2px; }
    
            /* Visualizer */
            .viz-canvas-container {
                background: white; border: 1px solid #cfd8dc; border-radius: 8px;
                padding: 20px; text-align: center; margin: 20px 0;
                box-shadow: inset 0 0 20px rgba(0,0,0,0.02);
            }
            canvas { max-width: 100%; box-shadow: 0 2px 5px rgba(0,0,0,0.05); background: white; }
    
            /* EtD Layout */
            .etd-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
            .etd-box { background: #fcfcfc; padding: 15px; border: 1px solid #eee; border-radius: 6px; page-break-inside: avoid; }
            .etd-box h4 { margin: 0 0 10px 0; font-size: 1em; color: var(--primary); }
    
            /* Buttons */
            .btn {
                padding: 10px 20px; border: none; border-radius: 4px; font-weight: bold; cursor: pointer;
                background: var(--primary); color: white; transition: 0.2s;
            }
            .btn:hover { background: var(--primary-dark); box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
            .btn:disabled { background: #b0bec5; cursor: not-allowed; box-shadow: none; }
            .btn-outline { background: transparent; border: 2px solid white; color: white; }
            .btn-outline:hover { background: rgba(255,255,255,0.1); }
            .btn-add { background: #2e7d32; }
    
            /* Deep Dive */
            .deep-dive {
                background: white; border-left: 4px solid #78909c; padding: 15px 20px; 
                margin-bottom: 15px; border-radius: 0 4px 4px 0; box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            }
            .deep-dive summary { font-weight: bold; cursor: pointer; color: #455a64; }
            .deep-content { margin-top: 10px; font-size: 0.9em; line-height: 1.7; color: #333; }
            .guyatt-box { background: #f3e5f5; padding: 10px; border-left: 4px solid #ab47bc; margin: 10px 0; }
            .pitfall { background: #ffebee; padding: 10px; border-left: 4px solid #ef5350; margin: 10px 0; }
    
            /* PDF */
            #pdf-content-area { background: white; padding: 20px; }
        </style>
    </head>
    <body>
    
    <header>
        <div>
            <div class="app-title">Core GRADE Master</div>
            <div class="app-version">v23.1: Stable Final</div>
        </div>
        <button class="btn btn-outline" id="btn-export-pdf" onclick="exportEtDPDF()">📄 EtDをPDF保存</button>
    </header>
    
    <div class="container">
        <nav class="sidebar">
            <div class="nav-item active" onclick="showPage('pico')"><span class="nav-icon">1️⃣</span> PICO設定</div>
            <div class="nav-item" onclick="showPage('sof')"><span class="nav-icon">2️⃣</span> SoFテーブル入力</div>
            <div class="nav-item" onclick="showPage('etd')"><span class="nav-icon">3️⃣</span> EtD & Visualizer</div>
            <div class="nav-item" onclick="showPage('guide')"><span class="nav-icon">📚</span> GRADE解説ライブラリ</div>
        </nav>
    
        <main class="content">
            
            <div id="pico" class="page active">
                <h2>Step 1: PICO & 研究デザイン</h2>
                <div class="card">
                    <div class="form-row">
                        <div class="form-group">
                            <label>Population (対象集団)</label>
                            <input type="text" id="pico_p" placeholder="例: 重症敗血症患者">
                        </div>
                        <div class="form-group">
                            <label>Intervention (介入)</label>
                            <input type="text" id="pico_i" placeholder="例: 新規薬剤A">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Comparator (比較対照)</label>
                            <input type="text" id="pico_c" placeholder="例: 標準治療">
                        </div>
                        <div class="form-group">
                            <label>Study Design (開始点)</label>
                            <select id="study_design">
                                <option value="RCT">RCT (High Start)</option>
                                <option value="OBS">観察研究 (Low Start)</option>
                            </select>
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <button class="btn" onclick="showPage('sof')">次へ: SoF入力 →</button>
                    </div>
                </div>
                
                <div class="deep-dive">
                    <summary>💡 Core GRADE解説: 相対効果と絶対効果の区別</summary>
                    <div class="deep-content">
                        <p>Core GRADEでは、PICO策定時に相対効果と絶対効果の違いを明確に区別することを推奨しています。</p>
                        <ul>
                            <li><strong>相対効果 (Relative Effect):</strong> 患者背景によって変わらないことが多い。</li>
                            <li><strong>絶対効果 (Absolute Effect):</strong> ベースラインリスクに依存するため、重症度などで大きく異なる。推奨決定には絶対効果が最重要。</li>
                        </ul>
                    </div>
                </div>
            </div>
    
            <div id="sof" class="page">
                <h2>Step 2: Summary of Findings (SoF) 作成</h2>
                <p><strong>計算フロー:</strong> 対照群(/1000) × 相対効果(RR) = 介入群(/1000) → 絶対効果差</p>
                
                <div class="card card-highlight">
                    <div class="form-row" style="align-items:flex-end;">
                        <div class="form-group" style="flex:2;">
                            <label>新規アウトカム名</label>
                            <input type="text" id="new_outcome_name" placeholder="例: 28日死亡率">
                        </div>
                        <div class="form-group">
                            <label>重要度 (1-9)</label>
                            <select id="new_outcome_imp">
                                <option value="9">9: Critical (重大)</option>
                                <option value="8">8: Critical (重大)</option>
                                <option value="7">7: Critical (重大)</option>
                                <option value="6">6: Important (重要)</option>
                                <option value="5">5: Important (重要)</option>
                                <option value="4">4: Important (重要)</option>
                            </select>
                        </div>
                        <button class="btn btn-add" onclick="addOutcome()">+ 追加</button>
                    </div>
                </div>
    
                <div class="sof-container">
                    <table class="sof-table">
                        <thead>
                            <tr>
                                <th style="width:15%;">アウトカム & Imp</th>
                                <th style="width:12%; background:#eceff1; color:#333;">① 対照群<br>(/1000人)</th>
                                <th style="width:20%; background:#cfd8dc; color:#333;">② 相対効果<br>(RR & 95%CI)</th>
                                <th style="width:12%; background:#eceff1; color:#333;">③ 介入群<br>(/1000人)</th>
                                <th style="width:18%; background:#b0bec5; color:#333;">④ 絶対効果差<br>(/1000人 & 95%CI)</th>
                                <th style="width:8%;">MID</th>
                                <th style="width:15%;">確実性</th>
                            </tr>
                        </thead>
                        <tbody id="sof_tbody">
                            </tbody>
                    </table>
                </div>
                
                <div class="pitfall" style="margin-top:15px; border-color:#d32f2f;">
                    <strong>⚠️ 免責事項:</strong><br>
                    本アプリは、解説と評価のアシストをするものであり、アウトカムごと評価できません。
                </div>
    
                <div style="margin-top:20px; text-align:right;">
                    <button class="btn" onclick="showPage('etd')">次へ: EtD & Visualizer →</button>
                </div>
            </div>
    
            <div id="etd" class="page">
                <h2>Step 3: Evidence to Decision (EtD) & 推奨</h2>
                
                <div id="etd-content-to-pdf">
                    
                    <div style="background:#e3f2fd; padding:10px; margin-bottom:15px; border-left:5px solid #0d47a1;">
                        <h3 style="margin:0; border:none; padding:0; font-size:1.1em; color:#0d47a1;">Evidence to Decision Report</h3>
                        <div id="pdf-header-pico" style="font-size:0.9em; margin-top:5px; color:#555;"></div>
                    </div>
    
                    <div class="viz-canvas-container">
                        <h3 style="margin-top:0;">📊 エビデンス・プロファイル (Forest Plot)</h3>
                        <p>SoFで計算された絶対効果差と95%信頼区間、MIDを表示します。</p>
                        <canvas id="viz_canvas" width="800" height="400"></canvas>
                        <div style="margin-top:10px; font-size:0.8em; color:#666;">
                            <span style="display:inline-block; width:12px; height:12px; background:#0d47a1; margin-right:5px;"></span>点推定値
                            <span style="display:inline-block; width:40px; height:2px; background:#0d47a1; vertical-align:middle; margin:0 5px;"></span>95%信頼区間
                            <span style="display:inline-block; width:2px; height:12px; background:#d32f2f; margin-left:10px; margin-right:5px;"></span>MIDライン
                        </div>
                    </div>
    
                    <div class="card" style="border:none; box-shadow:none; padding:0;">
                        <h3 style="border-bottom:1px solid #ccc; padding-bottom:5px;">1. 主要な基準 (Main Criteria)</h3>
                        <div class="etd-grid">
                            <div class="etd-box">
                                <h4>⚖️ 益と害のバランス</h4>
                                <select id="etd_balance" class="w-100">
                                    <option value="neutral">同等 / 不明</option>
                                    <option value="favors_i">介入有利 (Benefits > Harms)</option>
                                    <option value="favors_c">対照有利 (Harms > Benefits)</option>
                                </select>
                                <p style="font-size:0.8em; margin-top:5px; color:#666;">絶対効果の差に基づき判断</p>
                            </div>
                            <div class="etd-box">
                                <h4>🔍 エビデンスの確実性</h4>
                                <select id="etd_certainty" class="w-100">
                                    <option value="low">Low (低い)</option>
                                    <option value="very_low">Very Low (非常に低い)</option>
                                    <option value="moderate">Moderate (中等度)</option>
                                    <option value="high">High (高い)</option>
                                </select>
                                <p style="font-size:0.8em; margin-top:5px; color:#666;">全アウトカムの最低値を考慮</p>
                            </div>
                            <div class="etd-box">
                                <h4>❤️ 価値観と意向</h4>
                                <select id="etd_values" class="w-100">
                                    <option value="no_var">ばらつき小 / 不確実性なし</option>
                                    <option value="var">ばらつき大 (重要な不確実性あり)</option>
                                </select>
                            </div>
                            <div class="etd-box">
                                <h4>🚑 問題の優先度</h4>
                                <select id="etd_priority" class="w-100">
                                    <option value="yes">優先度高い</option>
                                    <option value="no">低い</option>
                                    <option value="vary">状況による</option>
                                </select>
                            </div>
                        </div>
    
                        <h3 style="border-bottom:1px solid #ccc; padding-bottom:5px; margin-top:20px;">2. その他の考慮事項 (Options/Contextual)</h3>
                        <div class="etd-grid">
                            <div class="etd-box">
                                <h4>💰 資源・コスト</h4>
                                <label>費用対効果:</label>
                                <select id="etd_cost_eff"><option>不明/変化なし</option><option>介入有利</option><option>対照有利</option></select>
                                <label style="margin-top:5px;">資源の確実性:</label>
                                <select id="etd_res_cert"><option>Low</option><option>High</option></select>
                            </div>
                            <div class="etd-box">
                                <h4>🌍 公平性・受容性・実行可能性</h4>
                                <label>公平性:</label>
                                <select id="etd_equity"><option>影響なし</option><option>格差縮小</option><option>格差拡大</option></select>
                                <label style="margin-top:5px;">受容性:</label>
                                <select id="etd_accept"><option>あり</option><option>なし</option><option>不明</option></select>
                                <label style="margin-top:5px;">実行可能性:</label>
                                <select id="etd_feasible"><option>あり</option><option>なし</option><option>不明</option></select>
                            </div>
                        </div>
    
                        <div style="background:#e8f5e9; padding:15px; border-radius:8px; border:1px solid #c8e6c9; margin-top:30px;">
                            <h3 style="margin-top:0; border:none; padding:0; color:#2e7d32;">🏁 最終推奨 (Recommendation)</h3>
                            <div class="form-row">
                                <button class="btn" style="background:#2e7d32; flex:1;" onclick="setRec('強く推奨する')">Strong FOR</button>
                                <button class="btn" style="background:#43a047; flex:1;" onclick="setRec('条件付きで推奨する')">Conditional FOR</button>
                                <button class="btn" style="background:#f57f17; flex:1;" onclick="setRec('条件付きで推奨しない')">Conditional AGAINST</button>
                                <button class="btn" style="background:#c62828; flex:1;" onclick="setRec('強く推奨しない')">Strong AGAINST</button>
                            </div>
                            <div style="margin-top:15px;">
                                <label>推奨文ドラフト</label>
                                <textarea id="rec_text" rows="3" style="width:100%; border:1px solid #a5d6a7; background:white;"></textarea>
                            </div>
                        </div>
                    </div>
                </div></div>
    
            <div id="guide" class="page">
                <h2>📚 GRADE解説ライブラリ</h2>
                <p>Core GRADEの重要な概念や、ドメイン評価の考え方をまとめた資料です。</p>
    
                <div class="deep-dive">
                    <summary>1. バイアスリスク (Risk of Bias) の評価アルゴリズム</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>Core GRADE 4 (Unpacked) より:</strong><br>
                            「高リスク研究が含まれているだけで即座にグレードダウンするのは誤りです。エビデンス全体を支配しているかどうかが重要です。」
                        </div>
                        <ul>
                            <li><strong>Step 1:</strong> 高リスク研究の重みが65%以上か?</li>
                            <li><strong>Step 2:</strong> バイアスの方向性は結果を過大評価しているか?</li>
                            <li><strong>Step 3:</strong> 低リスク研究の結果と高リスク研究の結果に差があるか?(感度分析)</li>
                            <li>差がなく結果が頑健(Robust)であれば、グレードダウンは不要です。</li>
                        </ul>
                    </div>
                </div>
    
                <div class="deep-dive">
                    <summary>2. 不精確さ (Imprecision) の閾値とOIS</summary>
                    <div class="deep-content">
                        <div class="guyatt-box">
                            <strong>Core GRADE 2 より:</strong><br>
                            「信頼区間が閾値(NullまたはMID)をまたぐかどうかで判断します。」
                        </div>
                        <ul>
                            <li><strong>MID (Minimal Important Difference):</strong> 臨床的に重要な最小差。</li>
                            <li><strong>判定フロー:</strong>
                                <ol>
                                    <li>CIがMIDをまたぐ → グレードダウン (-1)</li>
                                    <li>CIがまたがないが、OIS(最適情報サイズ、例:イベント数300)を満たさない → CI比を確認</li>
                                    <li>RRのCI比 > 3 ならグレードダウン (-1)</li>
                                </ol>
                            </li>
                        </ul>
                    </div>
                </div>
    
                <div class="deep-dive">
                    <summary>3. エビデンスの確実性の連続性 (Close Call)</summary>
                    <div class="deep-content">
                        <p>確実性はHigh/Mod/Low/VeryLowの4段階ですが、実際には連続的なスペクトラムです。境界線上にある「際どい判断 (Close Call)」の場合は、その理由を明記することが透明性確保に重要です。</p>
                    </div>
                </div>
            </div>
    
        </main>
    </div>
    
    <script>
        // --- Data Store ---
        let appData = {
            pico: { p:'', i:'', c:'', design:'RCT' },
            outcomes: [] 
        };
    
        // --- Utils ---
        // Safe float parser that handles empty string as 0 or 1 depending on context
        const safeFloat = (val, def = 0) => {
            if(val === '' || val === null || val === undefined) return def;
            const num = parseFloat(val);
            return isNaN(num) ? def : num;
        };
    
        // --- Navigation ---
        function showPage(pageId) {
            document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
            document.getElementById(pageId).classList.add('active');
            document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
            
            // Update PDF Header on EtD Show
            if(pageId === 'etd') {
                try {
                    drawVisualizer();
                } catch(e) { console.error("Viz Error:", e); }
                updatePdfHeader();
            }
        }
    
        function updatePdfHeader() {
            const p = document.getElementById('pico_p').value || 'P';
            const i = document.getElementById('pico_i').value || 'I';
            const c = document.getElementById('pico_c').value || 'C';
            document.getElementById('pdf-header-pico').textContent = `Population: ${p} | Intervention: ${i} | Comparator: ${c}`;
        }
    
        // --- PDF Export ---
        function exportEtDPDF() {
            // Disable button to prevent double clicks
            const btn = document.getElementById('btn-export-pdf');
            btn.disabled = true;
            btn.innerText = '生成中...';
    
            // Ensure EtD page is visible
            showPage('etd');
            const element = document.getElementById('etd-content-to-pdf');
            
            const opt = {
                margin:       10,
                filename:     'EtD_Report.pdf',
                image:        { type: 'jpeg', quality: 0.98 },
                html2canvas:  { scale: 2, useCORS: true },
                jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
            };
    
            html2pdf().set(opt).from(element).save()
            .then(() => {
                alert('PDFの保存が完了しました。');
                btn.disabled = false;
                btn.innerText = '📄 EtDをPDF保存';
            })
            .catch(err => {
                console.error(err);
                alert('PDF生成中にエラーが発生しました。');
                btn.disabled = false;
                btn.innerText = '📄 EtDをPDF保存';
            });
        }
    
        // --- SoF Logic ---
        function addOutcome() {
            const nameInput = document.getElementById('new_outcome_name');
            const name = nameInput.value;
            if(!name) return alert('名前を入力してください');
            
            const outcome = {
                id: Date.now(),
                name: name,
                imp: document.getElementById('new_outcome_imp').value,
                
                base_events: '150', 
                rr: '0.8', 
                ci_low: '0.6', 
                ci_high: '1.0',
                
                // Calculated values
                int_events: 0,
                abs_diff: 0,
                abs_low: 0,
                abs_high: 0,
                
                mid: '20',
                cert: 'low' 
            };
            appData.outcomes.push(outcome);
            
            // Calc initial row
            recalcRow(appData.outcomes.length - 1);
            renderSoF();
            nameInput.value = '';
        }
    
        function recalcRow(index) {
            const o = appData.outcomes[index];
            const base = safeFloat(o.base_events, 0); // /1000
            const rr = safeFloat(o.rr, 1.0);
            const low = safeFloat(o.ci_low, rr);
            const high = safeFloat(o.ci_high, rr);
    
            // Calc Intervention Risk
            o.int_events = Math.round(base * rr);
    
            // Calc Absolute Difference
            o.abs_diff = Math.round(base * (rr - 1));
    
            // Calc Absolute CI
            o.abs_low = Math.round(base * (low - 1));
            o.abs_high = Math.round(base * (high - 1));
        }
    
        function renderSoF() {
            const tbody = document.getElementById('sof_tbody');
            tbody.innerHTML = '';
            
            appData.outcomes.forEach((o, index) => {
                const tr = document.createElement('tr');
                
                const certOpts = `
                    <option value="high" ${o.cert=='high'?'selected':''}>High ⊕⊕⊕⊕</option>
                    <option value="moderate" ${o.cert=='moderate'?'selected':''}>Mod ⊕⊕⊕◯</option>
                    <option value="low" ${o.cert=='low'?'selected':''}>Low ⊕⊕◯◯</option>
                    <option value="very_low" ${o.cert=='very_low'?'selected':''}>VLow ⊕◯◯◯</option>
                `;
    
                tr.innerHTML = `
                    <td>
                        <input type="text" value="${o.name}" onchange="updateData(${index}, 'name', this.value)" style="font-weight:bold;">
                        <div style="margin-top:5px;">
                            <span style="font-size:0.8em;">Imp:</span>
                            <select onchange="updateData(${index}, 'imp', this.value)" style="padding:2px;">
                                <option value="9" ${o.imp=='9'?'selected':''}>9 (Crit)</option>
                                <option value="7" ${o.imp=='7'?'selected':''}>7 (Crit)</option>
                                <option value="5" ${o.imp=='5'?'selected':''}>5 (Imp)</option>
                            </select>
                        </div>
                    </td>
                    <td>
                        <input type="number" value="${o.base_events}" onchange="updateData(${index}, 'base_events', this.value)" class="sof-input-md" placeholder="/1000">
                    </td>
                    <td>
                        <div class="sof-input-container">
                            <span class="sof-input-label">RR</span>
                            <input type="number" step="0.01" value="${o.rr}" onchange="updateData(${index}, 'rr', this.value)" style="width:60px;">
                        </div>
                        <div class="sof-input-container" style="margin-top:4px;">
                            <span class="sof-input-label">CI</span>
                            <input type="number" step="0.01" value="${o.ci_low}" onchange="updateData(${index}, 'ci_low', this.value)" class="sof-input-xs">
                            <span>-</span>
                            <input type="number" step="0.01" value="${o.ci_high}" onchange="updateData(${index}, 'ci_high', this.value)" class="sof-input-xs">
                        </div>
                    </td>
                    <td>
                        <span class="calc-value">${o.int_events}</span>
                    </td>
                    <td>
                        <span class="calc-value" style="color:${o.abs_diff<0?'#2e7d32':'#c62828'};">${o.abs_diff > 0 ? '+'+o.abs_diff : o.abs_diff}</span>
                        <span class="calc-sub">[${o.abs_low} to ${o.abs_high}]</span>
                    </td>
                    <td>
                        <input type="number" value="${o.mid}" onchange="updateData(${index}, 'mid', this.value)" class="sof-input-sm">
                    </td>
                    <td>
                        <select onchange="updateData(${index}, 'cert', this.value)" class="sof-select">
                            ${certOpts}
                        </select>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }
    
        function updateData(index, field, value) {
            appData.outcomes[index][field] = value;
            
            // Trigger recalc
            if(['base_events', 'rr', 'ci_low', 'ci_high'].includes(field)) {
                recalcRow(index);
                renderSoF();
            }
        }
    
        // --- Visualizer ---
        function drawVisualizer() {
            const canvas = document.getElementById('viz_canvas');
            if (!canvas) return;
            const ctx = canvas.getContext('2d');
            const w = canvas.width;
            const h = canvas.height;
            
            ctx.clearRect(0, 0, w, h);
            
            // Header
            ctx.fillStyle = '#e3f2fd'; ctx.fillRect(0, 0, w, 40);
            ctx.fillStyle = '#000'; ctx.font = 'bold 14px Arial';
            ctx.fillText("Outcome", 20, 25);
            ctx.fillText("Certainty", 200, 25);
            ctx.fillText("Absolute Effect Diff (/1000) & MID", 400, 25);
    
            const targets = appData.outcomes.filter(o => parseInt(o.imp) >= 4);
            if(targets.length === 0) {
                ctx.fillStyle = '#666';
                ctx.fillText("No important outcomes to display.", w/2 - 100, h/2);
                return;
            }
    
            const rowH = 60;
            const startY = 60;
            const centerX = 500;
            const scale = 2; 
    
            targets.forEach((o, i) => {
                const y = startY + (i * rowH);
                
                ctx.fillStyle = '#333'; ctx.font = '14px Arial';
                ctx.fillText(o.name, 20, y);
                
                let certColor = '#757575';
                if(o.cert === 'high') certColor = '#2e7d32';
                if(o.cert === 'moderate') certColor = '#fbc02d';
                if(o.cert === 'low') certColor = '#f57f17';
                if(o.cert === 'very_low') certColor = '#c62828';
                
                ctx.fillStyle = certColor;
                ctx.fillRect(200, y-10, 80, 20);
                ctx.fillStyle = '#fff'; ctx.font = 'bold 11px Arial';
                ctx.fillText(o.cert.toUpperCase().replace('_',' '), 215, y+4);
    
                // Graph Values
                const val = safeFloat(o.abs_diff, 0);
                const low = safeFloat(o.abs_low, val);
                const high = safeFloat(o.abs_high, val);
                const mid = safeFloat(o.mid, 0);
    
                const xVal = centerX + (val * scale);
                const xLow = centerX + (low * scale);
                const xHigh = centerX + (high * scale);
    
                // Null Line
                ctx.beginPath(); ctx.moveTo(centerX, 40); ctx.lineTo(centerX, h); 
                ctx.strokeStyle = '#cfd8dc'; ctx.lineWidth = 1; ctx.stroke();
    
                // MID Lines
                if(mid > 0) {
                    ctx.strokeStyle = '#d32f2f'; ctx.lineWidth = 1; ctx.setLineDash([2, 2]);
                    ctx.beginPath(); 
                    ctx.moveTo(centerX - mid*scale, y-20); ctx.lineTo(centerX - mid*scale, y+20);
                    ctx.moveTo(centerX + mid*scale, y-20); ctx.lineTo(centerX + mid*scale, y+20);
                    ctx.stroke();
                    ctx.setLineDash([]);
                }
    
                // CI Line
                ctx.beginPath(); ctx.moveTo(xLow, y); ctx.lineTo(xHigh, y);
                ctx.strokeStyle = '#0d47a1'; ctx.lineWidth = 3; ctx.stroke();
    
                // Point
                ctx.beginPath(); ctx.arc(xVal, y, 5, 0, Math.PI*2);
                ctx.fillStyle = '#0d47a1'; ctx.fill();
                
                // Text Label
                ctx.fillStyle = '#333'; ctx.font = '11px Arial';
                const label = (val > 0 ? "+"+val : val) + " [" + low + ", " + high + "]";
                ctx.fillText(label, xVal - 20, y - 10);
            });
            
            ctx.fillStyle = '#666';
            ctx.fillText("Favors Control ← 0 → Favors Intervention", centerX - 100, h - 10);
        }
    
        // --- Recommendation ---
        function setRec(text) {
            const p = document.getElementById('pico_p').value || '患者';
            const i = document.getElementById('pico_i').value || '介入';
            document.getElementById('rec_text').value = `${p}に対して、パネルは${i}を${text}。`;
        }
    
        // Initialize
        addOutcome(); 
    </script>
    
    </body>
    </html>

    あなたへのおすすめ