
N対N配車(gradとdiv)📒まとめ①📒
gradのエリアクラスタリング版、divを入れてN対N配車に拡張してみた。
デモ版としては面白い。
ちなみに、gradもdivも理解してない w

まずGemini Proで作る。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>配車シミュレーター</title>
<style>
:root { --bg-dark: #0B1420; --line-dark: #1C2E3F; --text-dark: #E7EDF3; }
body { font-family: sans-serif; margin: 0; padding: 10px 15px; background-color: #f0f2f5; display: flex; flex-direction: column; height: 100vh; box-sizing: border-box;}
h2 { font-size: 1.1em; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-top: 0; }
.tabs { display: flex; gap: 5px; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 0; }
.tab-btn { background: #ecf0f1; border: 1px solid #bdc3c7; border-bottom: none; color: #7f8c8d; padding: 8px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: bold; width: auto; font-size: 0.9em;}
.tab-btn:hover { background: #e0e6ed; }
.tab-btn.active { background: #3498db; color: #fff; border-color: #3498db; }
.layout-container { display: flex; gap: 15px; flex: 1; overflow: hidden; }
.panel { background: #fff; border-radius: 8px; padding: 15px; display: flex; flex-direction: column; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.panel-left { flex: 1.2; overflow-y: auto; }
.panel-center { flex: 1.5; background: #fafafa; overflow-y: auto; display: flex; flex-direction: column;}
.panel-right { flex: 1.6; overflow-y: auto; }
.layout-container.map-only .panel-left { display: none; }
.layout-container.map-only .panel-right { display: none; }
.layout-container.map-only .panel-center { flex: 1; }
button { background: #3498db; color: #fff; border: none; padding: 10px; border-radius: 4px; cursor: pointer; width: 100%; font-weight: bold; }
button:hover { background: #2980b9; }
table { width: 100%; border-collapse: collapse; font-size: 0.85em; margin-bottom: 10px; }
th, td { border: 1px solid #ddd; padding: 5px; text-align: center; }
th { background-color: #ecf0f1; position: sticky; top: 0; }
.svg-wrapper { flex: 1; background: var(--bg-dark); border-radius: 8px; position: relative; min-height: 400px; border: 1px solid var(--line-dark); overflow: hidden;}
svg { width: 100%; height: 100%; display: block; cursor: grab;}
svg:active { cursor: grabbing; }
.ward-label { fill: #4A5C70; font-size: 10px; font-weight: bold; pointer-events: none; }
.truck-header { color: #fff; font-weight: bold; }
.badge { padding: 3px 6px; border-radius: 3px; font-size: 0.8em; color: #fff; display: inline-block;}
.badge.seq { background: #3498db; }
.badge.nest { background: #9b59b6; }
.btn-cut { background: #e74c3c; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-cut:hover { background: #c0392b; }
.btn-restore { background: #7f8c8d; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-restore:hover { background: #95a5a6; }
/* マップ操作用UI */
.map-controls { position: absolute; top: 10px; right: 10px; display: flex; gap: 5px; z-index: 10; }
.map-controls button { background: rgba(255,255,255,0.9); color: #2c3e50; border: 1px solid #bdc3c7; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; width: auto; font-size: 14px;}
.map-controls button:hover { background: #ecf0f1; }
/* ルート表示切替パネル */
.route-filters { position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.9); border: 1px solid #bdc3c7; border-radius: 6px; padding: 10px; z-index: 10; display: flex; flex-direction: column; gap: 5px; font-size: 13px; max-height: 80%; overflow-y: auto; box-shadow: 0 2px 6px rgba(0,0,0,0.15);}
.route-filters strong { color: #2c3e50; margin-bottom: 5px; display: block; border-bottom: 1px solid #ddd; padding-bottom: 4px; }
.filter-label { display: flex; align-items: center; gap: 6px; cursor: pointer; color: #333; }
.color-box { width: 14px; height: 14px; border-radius: 3px; }
</style>
</head>
<body>
<div class="tabs">
<button class="tab-btn active" id="tab-normal" onclick="switchView('normal')">📊 通常ビュー (操作・分割)</button>
<button class="tab-btn" id="tab-map" onclick="switchView('map-only')">🗺️ マップ全面 (ルート確認)</button>
</div>
<div class="layout-container" id="mainLayout">
<div class="panel panel-left">
<h2>1. 配送ペア設定</h2>
<div style="margin-bottom:15px; font-size:0.9em;">
<label>配車ベース車格:
<select id="capSelect" onchange="generateData()">
<option value="4">4t</option>
<option value="8" selected>8t</option>
<option value="13">13t</option>
</select>
</label>
<br>
<span style="color:#7f8c8d;">※混載(入れ子)の判定上限に使用します</span>
<button style="margin-top:10px;" onclick="generateData()">🎲 データを再生成</button>
</div>
<table>
<thead><tr><th>ID</th><th>品名</th><th>発 +</th><th>着 -</th><th>量(t)</th></tr></thead>
<tbody id="initialBody"></tbody>
</table>
</div>
<div class="panel panel-center">
<h2>2. マップ (ルート確認)</h2>
<div class="svg-wrapper" id="svgWrap">
<!-- 表示切替パネル -->
<div id="routeFilters" class="route-filters"></div>
<!-- ズーム操作 -->
<div class="map-controls">
<button onclick="zoomMap(0.8)" title="拡大">+</button>
<button onclick="zoomMap(1.25)" title="縮小">-</button>
<button onclick="resetMap()" title="初期表示に戻す">リセット</button>
</div>
<svg id="mapSvg" viewBox="0 0 430 520" preserveAspectRatio="xMidYMid meet"></svg>
</div>
</div>
<div class="panel panel-right">
<h2>3. 実行ルート (手動調整)</h2>
<table id="dispatchTable">
<tbody id="dispatchBody"><tr><td>計算結果がここに表示されます</td></tr></tbody>
</table>
</div>
</div>
<script>
const WARDS = {"千代田":[0.5,-0.5],"中央":[2.0,-1.0],"港":[0.0,-4.5],"新宿":[-6.0,0.5],"文京":[-1.0,3.5],"豊島":[-5.0,5.5]};
const productTypes = ["食料", "飲料", "建材", "雑貨", "家電"];
const PALETTE = ["#3498db", "#e67e22", "#2ecc71", "#9b59b6", "#f1c40f", "#1abc9c", "#e74c3c", "#34495e"];
const svgNS="http://www.w3.org/2000/svg";
function el(tag, attrs){ const e=document.createElementNS(svgNS,tag); for(const k in attrs) e.setAttribute(k, attrs[k]); return e; }
let RAW = [], n, C, edgeType, height, gradParent;
let userCuts = {};
let sx, sy;
// マップ表示状態管理用
let visibleRoutes = {};
let currentFinalRoot = [];
let currentRootColors = {};
// --- マップのズーム・パンスクロール制御 ---
const svg = document.getElementById('mapSvg');
const DEFAULT_VB = { x: 0, y: 0, w: 430, h: 520 };
let vb = { ...DEFAULT_VB };
let isDown = false;
let startX, startY;
function updateViewBox() {
svg.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`);
}
function resetMap() {
vb = { ...DEFAULT_VB };
updateViewBox();
}
function zoomMap(factor) {
let cx = vb.x + vb.w / 2;
let cy = vb.y + vb.h / 2;
vb.w *= factor;
vb.h *= factor;
vb.x = cx - vb.w / 2;
vb.y = cy - vb.h / 2;
updateViewBox();
}
svg.addEventListener('mousedown', (e) => {
isDown = true;
startX = e.clientX;
startY = e.clientY;
});
window.addEventListener('mouseup', () => { isDown = false; });
window.addEventListener('mousemove', (e) => {
if (!isDown) return;
e.preventDefault();
let rect = svg.getBoundingClientRect();
let scaleX = vb.w / rect.width;
let scaleY = vb.h / rect.height;
vb.x -= (e.clientX - startX) * scaleX;
vb.y -= (e.clientY - startY) * scaleY;
updateViewBox();
startX = e.clientX;
startY = e.clientY;
});
svg.addEventListener('wheel', (e) => {
e.preventDefault();
let rect = svg.getBoundingClientRect();
let mouseX = vb.x + (e.clientX - rect.left) * (vb.w / rect.width);
let mouseY = vb.y + (e.clientY - rect.top) * (vb.h / rect.height);
let zoomFactor = e.deltaY > 0 ? 1.1 : 0.9;
vb.w *= zoomFactor;
vb.h *= zoomFactor;
vb.x = mouseX - (e.clientX - rect.left) * (vb.w / rect.width);
vb.y = mouseY - (e.clientY - rect.top) * (vb.h / rect.height);
updateViewBox();
}, { passive: false });
// ------------------------------------------
function switchView(mode) {
const layout = document.getElementById('mainLayout');
const tabNormal = document.getElementById('tab-normal');
const tabMap = document.getElementById('tab-map');
if (mode === 'map-only') {
layout.classList.add('map-only');
tabMap.classList.add('active');
tabNormal.classList.remove('active');
} else {
layout.classList.remove('map-only');
tabNormal.classList.add('active');
tabMap.classList.remove('active');
}
// 切り替え時にマップサイズが変わるためViewBoxを更新
setTimeout(updateViewBox, 50);
}
function generateData() {
let CAPACITY = +document.getElementById('capSelect').value;
const pts = []; let id = 0;
const wNames = Object.keys(WARDS);
for(let i=0; i<15; i++) {
let pw = wNames[Math.floor(Math.random()*wNames.length)];
let dw = wNames[Math.floor(Math.random()*wNames.length)];
if(pw === dw) dw = wNames[(wNames.indexOf(dw)+1)%wNames.length];
let px = WARDS[pw][0] + (Math.random()*2-1);
let py = WARDS[pw][1] + (Math.random()*2-1);
let dx = WARDS[dw][0] + (Math.random()*2-1);
let dy = WARDS[dw][1] + (Math.random()*2-1);
let d = +(CAPACITY * (0.2 + Math.random()*0.7)).toFixed(1);
pts.push({
id: id++, name: productTypes[Math.floor(Math.random()*productTypes.length)],
p_near: pw, p_x: px, p_y: py, d_near: dw, d_x: dx, d_y: dy, demand: d
});
}
RAW = pts;
userCuts = {};
visibleRoutes = {}; // 新規生成時は表示状態をリセット
resetMap();
renderLeftTable();
computePairGradient(CAPACITY);
}
function renderLeftTable() {
const tb = document.getElementById('initialBody');
tb.innerHTML = '';
RAW.forEach(p => {
tb.innerHTML += `<tr><td>#${p.id}</td><td>${p.name}</td><td>${p.p_near}</td><td>${p.d_near}</td><td>${p.demand}</td></tr>`;
});
}
function computePairGradient(CAPACITY) {
n = RAW.length;
C = Array.from({length:n}, ()=>new Array(n).fill(Infinity));
edgeType = Array.from({length:n}, ()=>new Array(n).fill(''));
for(let i=0; i<n; i++){
for(let j=0; j<n; j++){
if(i===j) continue;
let seqDist = Math.hypot(RAW[i].d_x - RAW[j].p_x, RAW[i].d_y - RAW[j].p_y);
let nestDist = Infinity;
if (RAW[i].demand + RAW[j].demand <= CAPACITY) {
nestDist = Math.hypot(RAW[i].p_x - RAW[j].p_x, RAW[i].p_y - RAW[j].p_y) +
Math.hypot(RAW[i].d_x - RAW[j].d_x, RAW[i].d_y - RAW[j].d_y) + 1.0;
}
if(seqDist <= nestDist) {
C[i][j] = seqDist; edgeType[i][j] = 'seq';
} else {
C[i][j] = nestDist; edgeType[i][j] = 'nest';
}
}
}
const BANDWIDTH = 3.0;
height = RAW.map((_, i) => {
let h = 0;
for(let j=0; j<n; j++) if(i!==j) h -= (RAW[j].demand) * Math.exp(-Math.min(C[i][j], C[j][i]) / BANDWIDTH);
return h;
});
gradParent = {};
for(let i=0; i<n; i++){
let lower = [...Array(n).keys()].filter(j => height[j] < height[i]);
if(lower.length === 0) continue;
let bestJ = lower[0], minC = C[i][bestJ];
for(let k=1; k<lower.length; k++){
if(C[i][lower[k]] < minC) { minC = C[i][lower[k]]; bestJ = lower[k]; }
}
gradParent[i] = bestJ;
}
const xs=[], ys=[];
RAW.forEach(p=>{ xs.push(p.p_x, p.d_x); ys.push(p.p_y, p.d_y); });
const xMin=Math.min(...xs)-1, xMax=Math.max(...xs)+1;
const yMin=Math.min(...ys)-1, yMax=Math.max(...ys)+1;
sx = (x)=> 30 + (x-xMin)/(xMax-xMin)*370;
sy = (y)=> 30 + (yMax-y)/(yMax-yMin)*460;
updateTopology();
}
function toggleCut(childId) {
if (userCuts[childId]) delete userCuts[childId];
else userCuts[childId] = true;
updateTopology();
}
// チェックボックスのON/OFF
function toggleRouteDisplay(rootId, isChecked) {
visibleRoutes[rootId] = isChecked;
drawSVG();
}
function toggleAllRoutes(isChecked) {
Object.keys(visibleRoutes).forEach(r => visibleRoutes[r] = isChecked);
// 全てのチェックボックスの見た目を同期
document.querySelectorAll('.route-chk').forEach(chk => chk.checked = isChecked);
drawSVG();
}
function updateTopology() {
currentFinalRoot = new Array(n);
for(let j=0; j<n; j++){
let cur = j;
while(gradParent[cur] !== undefined && !userCuts[cur]) {
cur = gradParent[cur];
}
currentFinalRoot[j] = cur;
}
let clusters = {};
for(let j=0; j<n; j++){ (clusters[currentFinalRoot[j]] ??= []).push(j); }
currentRootColors = {};
Object.keys(clusters).forEach((r, i) => {
currentRootColors[r] = PALETTE[i % PALETTE.length];
// 新しいルートができたらデフォルトで表示ON
if(visibleRoutes[r] === undefined) visibleRoutes[r] = true;
});
// なくなったルートの表示情報を整理
Object.keys(visibleRoutes).forEach(r => {
if(!clusters[r]) delete visibleRoutes[r];
});
buildRoutesAndFilters(clusters, currentRootColors);
drawSVG();
}
function drawSVG() {
svg.innerHTML = '';
const defs = el('defs',{});
svg.appendChild(defs);
Object.entries(WARDS).forEach(([name,[x,y]])=>{
svg.appendChild(el('text',{x:sx(x),y:sy(y)-15,class:'ward-label','text-anchor':'middle'})).textContent=name;
});
// 1. 各タスク自身の発→着線(グレー)
for(let i=0; i<n; i++) {
if (!visibleRoutes[currentFinalRoot[i]]) continue;
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[i].d_x), y2:sy(RAW[i].d_y),
stroke: '#bdc3c7', 'stroke-width': 2, opacity: 0.5
}));
}
// 2. 勾配によるつながり線
for(let i=0; i<n; i++){
if(gradParent[i] === undefined) continue;
let p = gradParent[i];
// i または p のどちらかが表示ONなら、関係性(切断マークなど)を描画範囲の対象にする
if (!visibleRoutes[currentFinalRoot[i]] && !visibleRoutes[currentFinalRoot[p]]) continue;
let type = edgeType[i][p];
if (userCuts[i]) {
let cx = (sx(RAW[i].d_x) + sx(RAW[p].p_x))/2;
let cy = (sy(RAW[i].d_y) + sy(RAW[p].p_y))/2;
let cutIcon = el('text', {x:cx, y:cy+4, 'text-anchor':'middle', fill:'#e74c3c', 'font-size':'16px', opacity:0.8});
cutIcon.textContent = '✂️';
svg.appendChild(cutIcon);
continue;
}
// 両方同じルート(切断されていない)かつ、そのルートが表示OFFならスキップ
if (!visibleRoutes[currentFinalRoot[i]]) continue;
let routeColor = currentRootColors[currentFinalRoot[i]];
if (type === 'seq') {
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 2, 'stroke-dasharray': '4,4'
}));
} else {
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].d_x), y2:sy(RAW[p].d_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
}
}
// 3. 発・着ノード描画
for(let i=0; i<n; i++){
if (!visibleRoutes[currentFinalRoot[i]]) continue;
let r = 5 + RAW[i].demand * 1.5;
let c = currentRootColors[currentFinalRoot[i]];
svg.appendChild(el('circle', { cx:sx(RAW[i].p_x), cy:sy(RAW[i].p_y), r:r, fill:c, stroke:'#fff', 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].p_x), y:sy(RAW[i].p_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '+';
svg.appendChild(el('circle', { cx:sx(RAW[i].d_x), cy:sy(RAW[i].d_y), r:r, fill:c, stroke:'#fff', 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].d_x), y:sy(RAW[i].d_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '-';
}
}
function buildRoutesAndFilters(clusters, rootColors) {
let dBody = document.getElementById('dispatchBody');
let filterContainer = document.getElementById('routeFilters');
dBody.innerHTML = '';
// チェックボックスパネルの構築
let filterHtml = '<strong>表示切替</strong>';
filterHtml += `<label class="filter-label" style="margin-bottom:8px;"><input type="checkbox" onchange="toggleAllRoutes(this.checked)" checked> 全て表示</label>`;
let truckId = 1;
let sortedRoots = Object.keys(clusters).sort((a,b) => clusters[b].length - clusters[a].length);
sortedRoots.forEach(r => {
let pts = clusters[r];
pts.sort((a, b) => height[b] - height[a]);
let routeColor = rootColors[r];
// フィルタ用チェックボックスの追加
let isChecked = visibleRoutes[r] ? "checked" : "";
filterHtml += `<label class="filter-label">
<input type="checkbox" class="route-chk" value="${r}" onchange="toggleRouteDisplay('${r}', this.checked)" ${isChecked}>
<div class="color-box" style="background:${routeColor}"></div> 第 ${truckId} 便
</label>`;
// 右ペインのテーブル行作成
dBody.innerHTML += `<tr class="truck-header" style="background:${routeColor};"><td colspan="6">🚚 第 ${truckId++} 便 (${pts.length}件)</td></tr>`;
dBody.innerHTML += `<tr style="background:#eee; font-size:0.9em;"><th>ID</th><th>積地</th><th>降地</th><th>量(t)</th><th>状態</th><th>操作</th></tr>`;
pts.forEach(i => {
let p = gradParent[i];
let badge = "";
let actionBtn = "";
if (p !== undefined) {
if (!userCuts[i]) {
let tType = edgeType[i][p];
badge = tType === 'seq' ? '<span class="badge seq">直列</span>' : '<span class="badge nest">混載</span>';
actionBtn = `<button class="btn-cut" onclick="toggleCut(${i})">✂️ 分割</button>`;
}
}
if (userCuts[i]) {
actionBtn = `<button class="btn-restore" onclick="toggleCut(${i})">🔗 繋ぐ</button>`;
}
dBody.innerHTML += `<tr>
<td>#${RAW[i].id}</td>
<td>${RAW[i].p_near}</td>
<td>${RAW[i].d_near}</td>
<td>${RAW[i].demand} t</td>
<td>${badge}</td>
<td>${actionBtn}</td>
</tr>`;
});
});
filterContainer.innerHTML = filterHtml;
}
generateData();
</script>
</body>
</html>更にClaude Opus5で直す。
既存の見た目はそのまま、3点の修正を入れます。入れた変更は3点です。
① 車格変更で荷物セットが消えない
generateData() を「荷物を作る」と「判定を引き直す」に割りました。車格セレクタは recompute() を呼ぶだけなので、同じ15件のまま 4t → 8t → 13t と振って混載の入り方がどう変わるかを追えます。✂️の切断指定は荷物単位の意思なので保持、同点の親指定だけは候補の顔ぶれが変わるので破棄しています。
② nest鎖の累積容量
Union-Find を入れました。nestエッジを C の小さい順に処理して、繋いだ塊の合計が車格を超えるならその縁を混載から直列に格下げします(切るのではなく順番に回れば積載は競合しないので)。格下げされた縁は表に「容量で直列化」バッジ、マップに⚖の印が出ます。各便のヘッダーに「最大同時積載 ○t ≦ 車格」を出したので超えていないことが一目で確認できます。
③ 同点の可視化と手動切替
最良候補の 8%+0.3 以内に入る候補を tieCandidates として全部残し、握り潰さなくしました。該当箇所は表に⚡僅差バッジとプルダウン(候補IDと距離、混/直の別を表示)、マップに⚡が出ます。プルダウンで親を選び直すと即座にトポロジーが再計算されます。候補は必ず自分より terrain が低い点だけなので、手で選び直しても循環は起きません。
ついでに height というグローバル変数名を terrain に変えました(KDEの高さ場という意味が名前から分かるように、というだけです)。
「最大同時積載」の列が全便で車格以下に収まっているか、そこだけ動かして確認してもらえれば②は効いているはずです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>配車シミュレーター rev.2</title>
<style>
:root { --bg-dark: #0B1420; --line-dark: #1C2E3F; --text-dark: #E7EDF3; }
body { font-family: sans-serif; margin: 0; padding: 10px 15px; background-color: #f0f2f5; display: flex; flex-direction: column; height: 100vh; box-sizing: border-box;}
h2 { font-size: 1.1em; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-top: 0; }
.tabs { display: flex; gap: 5px; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 0; }
.tab-btn { background: #ecf0f1; border: 1px solid #bdc3c7; border-bottom: none; color: #7f8c8d; padding: 8px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: bold; width: auto; font-size: 0.9em;}
.tab-btn:hover { background: #e0e6ed; }
.tab-btn.active { background: #3498db; color: #fff; border-color: #3498db; }
.layout-container { display: flex; gap: 15px; flex: 1; overflow: hidden; }
.panel { background: #fff; border-radius: 8px; padding: 15px; display: flex; flex-direction: column; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.panel-left { flex: 1.2; overflow-y: auto; }
.panel-center { flex: 1.5; background: #fafafa; overflow-y: auto; display: flex; flex-direction: column;}
.panel-right { flex: 1.9; overflow-y: auto; }
.layout-container.map-only .panel-left { display: none; }
.layout-container.map-only .panel-right { display: none; }
.layout-container.map-only .panel-center { flex: 1; }
button { background: #3498db; color: #fff; border: none; padding: 10px; border-radius: 4px; cursor: pointer; width: 100%; font-weight: bold; }
button:hover { background: #2980b9; }
table { width: 100%; border-collapse: collapse; font-size: 0.85em; margin-bottom: 10px; }
th, td { border: 1px solid #ddd; padding: 5px; text-align: center; }
th { background-color: #ecf0f1; position: sticky; top: 0; }
.svg-wrapper { flex: 1; background: var(--bg-dark); border-radius: 8px; position: relative; min-height: 400px; border: 1px solid var(--line-dark); overflow: hidden;}
svg { width: 100%; height: 100%; display: block; cursor: grab;}
svg:active { cursor: grabbing; }
.ward-label { fill: #4A5C70; font-size: 10px; font-weight: bold; pointer-events: none; }
.truck-header { color: #fff; font-weight: bold; }
.badge { padding: 3px 6px; border-radius: 3px; font-size: 0.8em; color: #fff; display: inline-block;}
.badge.seq { background: #3498db; }
.badge.nest { background: #9b59b6; }
.badge.demote { background: #e67e22; }
.badge.tie { background: #c0392b; }
.btn-cut { background: #e74c3c; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-cut:hover { background: #c0392b; }
.btn-restore { background: #7f8c8d; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-restore:hover { background: #95a5a6; }
.sel-parent { font-size: 0.85em; max-width: 110px; }
.sel-parent.tie { border: 2px solid #c0392b; background: #fdf2f0; }
.cap-note { font-size: 0.85em; color: #7f8c8d; }
.cap-over { color: #c0392b; font-weight: bold; }
/* マップ操作用UI */
.map-controls { position: absolute; top: 10px; right: 10px; display: flex; gap: 5px; z-index: 10; }
.map-controls button { background: rgba(255,255,255,0.9); color: #2c3e50; border: 1px solid #bdc3c7; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; width: auto; font-size: 14px;}
.map-controls button:hover { background: #ecf0f1; }
/* ルート表示切替パネル */
.route-filters { position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.9); border: 1px solid #bdc3c7; border-radius: 6px; padding: 10px; z-index: 10; display: flex; flex-direction: column; gap: 5px; font-size: 13px; max-height: 80%; overflow-y: auto; box-shadow: 0 2px 6px rgba(0,0,0,0.15);}
.route-filters strong { color: #2c3e50; margin-bottom: 5px; display: block; border-bottom: 1px solid #ddd; padding-bottom: 4px; }
.filter-label { display: flex; align-items: center; gap: 6px; cursor: pointer; color: #333; }
.color-box { width: 14px; height: 14px; border-radius: 3px; }
</style>
</head>
<body>
<div class="tabs">
<button class="tab-btn active" id="tab-normal" onclick="switchView('normal')">📊 通常ビュー (操作・分割)</button>
<button class="tab-btn" id="tab-map" onclick="switchView('map-only')">🗺️ マップ全面 (ルート確認)</button>
</div>
<div class="layout-container" id="mainLayout">
<div class="panel panel-left">
<h2>1. 配送ペア設定</h2>
<div style="margin-bottom:15px; font-size:0.9em;">
<label>配車ベース車格:
<select id="capSelect" onchange="recompute()">
<option value="4">4t</option>
<option value="8" selected>8t</option>
<option value="13">13t</option>
</select>
</label>
<br>
<span class="cap-note">※車格を変えても荷物セットは保持され、混載判定だけが引き直されます</span>
<button style="margin-top:10px;" onclick="generateData()">🎲 データを再生成</button>
</div>
<table>
<thead><tr><th>ID</th><th>品名</th><th>発 +</th><th>着 -</th><th>量(t)</th></tr></thead>
<tbody id="initialBody"></tbody>
</table>
</div>
<div class="panel panel-center">
<h2>2. マップ (ルート確認)</h2>
<div class="svg-wrapper" id="svgWrap">
<div id="routeFilters" class="route-filters"></div>
<div class="map-controls">
<button onclick="zoomMap(0.8)" title="拡大">+</button>
<button onclick="zoomMap(1.25)" title="縮小">-</button>
<button onclick="resetMap()" title="初期表示に戻す">リセット</button>
</div>
<svg id="mapSvg" viewBox="0 0 430 520" preserveAspectRatio="xMidYMid meet"></svg>
</div>
</div>
<div class="panel panel-right">
<h2>3. 実行ルート (手動調整)</h2>
<table id="dispatchTable">
<tbody id="dispatchBody"><tr><td>計算結果がここに表示されます</td></tr></tbody>
</table>
</div>
</div>
<script>
const WARDS = {"千代田":[0.5,-0.5],"中央":[2.0,-1.0],"港":[0.0,-4.5],"新宿":[-6.0,0.5],"文京":[-1.0,3.5],"豊島":[-5.0,5.5]};
const productTypes = ["食料", "飲料", "建材", "雑貨", "家電"];
const PALETTE = ["#3498db", "#e67e22", "#2ecc71", "#9b59b6", "#f1c40f", "#1abc9c", "#e74c3c", "#34495e"];
const svgNS="http://www.w3.org/2000/svg";
function el(tag, attrs){ const e=document.createElementNS(svgNS,tag); for(const k in attrs) e.setAttribute(k, attrs[k]); return e; }
// 同点判定のしきい値:最良候補に対してこの範囲内なら「僅差」とみなす
const TIE_RATIO = 1.08;
const TIE_ABS = 0.30;
let RAW = [], n = 0, C, edgeType, terrain, gradParent;
let tieCandidates = {}; // i -> [候補jの配列](先頭が自動選択された最良)
let userCuts = {}; // i -> true(親との縁を切る)
let userParent = {}; // i -> j(同点の中から人間が選び直した親)
let demoted = {}; // i -> true(容量超過で混載→直列に格下げ)
let nestGroupLoad = {}; // i -> その時点の同時積載量(t)
let sx, sy;
let visibleRoutes = {};
let currentFinalRoot = [];
let currentRootColors = {};
// --- マップのズーム・パンスクロール制御 ---
const svg = document.getElementById('mapSvg');
const DEFAULT_VB = { x: 0, y: 0, w: 430, h: 520 };
let vb = { ...DEFAULT_VB };
let isDown = false;
let startX, startY;
function updateViewBox() {
svg.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`);
}
function resetMap() { vb = { ...DEFAULT_VB }; updateViewBox(); }
function zoomMap(factor) {
let cx = vb.x + vb.w / 2, cy = vb.y + vb.h / 2;
vb.w *= factor; vb.h *= factor;
vb.x = cx - vb.w / 2; vb.y = cy - vb.h / 2;
updateViewBox();
}
svg.addEventListener('mousedown', (e) => { isDown = true; startX = e.clientX; startY = e.clientY; });
window.addEventListener('mouseup', () => { isDown = false; });
window.addEventListener('mousemove', (e) => {
if (!isDown) return;
e.preventDefault();
let rect = svg.getBoundingClientRect();
vb.x -= (e.clientX - startX) * (vb.w / rect.width);
vb.y -= (e.clientY - startY) * (vb.h / rect.height);
updateViewBox();
startX = e.clientX; startY = e.clientY;
});
svg.addEventListener('wheel', (e) => {
e.preventDefault();
let rect = svg.getBoundingClientRect();
let mouseX = vb.x + (e.clientX - rect.left) * (vb.w / rect.width);
let mouseY = vb.y + (e.clientY - rect.top) * (vb.h / rect.height);
let zoomFactor = e.deltaY > 0 ? 1.1 : 0.9;
vb.w *= zoomFactor; vb.h *= zoomFactor;
vb.x = mouseX - (e.clientX - rect.left) * (vb.w / rect.width);
vb.y = mouseY - (e.clientY - rect.top) * (vb.h / rect.height);
updateViewBox();
}, { passive: false });
function switchView(mode) {
const layout = document.getElementById('mainLayout');
const tabNormal = document.getElementById('tab-normal');
const tabMap = document.getElementById('tab-map');
if (mode === 'map-only') {
layout.classList.add('map-only');
tabMap.classList.add('active'); tabNormal.classList.remove('active');
} else {
layout.classList.remove('map-only');
tabNormal.classList.add('active'); tabMap.classList.remove('active');
}
setTimeout(updateViewBox, 50);
}
function currentCapacity() { return +document.getElementById('capSelect').value; }
/* ===== 修正① データ生成と再計算を分離 =====
generateData() : 荷物セットそのものを作り直す(🎲ボタンのみ)
recompute() : 荷物セットは据え置きで、車格に応じた判定だけ引き直す */
function generateData() {
const CAPACITY = currentCapacity();
const pts = []; let id = 0;
const wNames = Object.keys(WARDS);
for(let i=0; i<15; i++) {
let pw = wNames[Math.floor(Math.random()*wNames.length)];
let dw = wNames[Math.floor(Math.random()*wNames.length)];
if(pw === dw) dw = wNames[(wNames.indexOf(dw)+1)%wNames.length];
pts.push({
id: id++, name: productTypes[Math.floor(Math.random()*productTypes.length)],
p_near: pw, p_x: WARDS[pw][0] + (Math.random()*2-1), p_y: WARDS[pw][1] + (Math.random()*2-1),
d_near: dw, d_x: WARDS[dw][0] + (Math.random()*2-1), d_y: WARDS[dw][1] + (Math.random()*2-1),
demand: +(CAPACITY * (0.2 + Math.random()*0.7)).toFixed(1)
});
}
RAW = pts;
userCuts = {}; userParent = {}; visibleRoutes = {};
resetMap();
renderLeftTable();
recompute();
}
function recompute() {
if (RAW.length === 0) { generateData(); return; }
// 車格が変わると同点の顔ぶれも変わるため、人間の親指定だけは無効化する。
// 「切る」判断は荷物単位の意思なので保持する。
userParent = {};
computePairGradient(currentCapacity());
}
function renderLeftTable() {
const tb = document.getElementById('initialBody');
tb.innerHTML = '';
RAW.forEach(p => {
tb.innerHTML += `<tr><td>#${p.id}</td><td>${p.name}</td><td>${p.p_near}</td><td>${p.d_near}</td><td>${p.demand}</td></tr>`;
});
}
function computePairGradient(CAPACITY) {
n = RAW.length;
C = Array.from({length:n}, ()=>new Array(n).fill(Infinity));
edgeType = Array.from({length:n}, ()=>new Array(n).fill(''));
for(let i=0; i<n; i++){
for(let j=0; j<n; j++){
if(i===j) continue;
let seqDist = Math.hypot(RAW[i].d_x - RAW[j].p_x, RAW[i].d_y - RAW[j].p_y);
let nestDist = Infinity;
if (RAW[i].demand + RAW[j].demand <= CAPACITY) {
nestDist = Math.hypot(RAW[i].p_x - RAW[j].p_x, RAW[i].p_y - RAW[j].p_y) +
Math.hypot(RAW[i].d_x - RAW[j].d_x, RAW[i].d_y - RAW[j].d_y) + 1.0;
}
if(seqDist <= nestDist) { C[i][j] = seqDist; edgeType[i][j] = 'seq'; }
else { C[i][j] = nestDist; edgeType[i][j] = 'nest'; }
}
}
const BANDWIDTH = 3.0;
terrain = RAW.map((_, i) => {
let h = 0;
for(let j=0; j<n; j++) if(i!==j) h -= (RAW[j].demand) * Math.exp(-Math.min(C[i][j], C[j][i]) / BANDWIDTH);
return h;
});
/* ===== 修正③ 同点(僅差)候補の列挙 =====
「唯一の下り方向」が無い箇所を握り潰さず、候補として全部残す。 */
gradParent = {};
tieCandidates = {};
for(let i=0; i<n; i++){
let lower = [...Array(n).keys()].filter(j => terrain[j] < terrain[i] && isFinite(C[i][j]));
if(lower.length === 0) continue;
lower.sort((a,b) => C[i][a] - C[i][b]);
gradParent[i] = lower[0];
const best = C[i][lower[0]];
const near = lower.filter(j => C[i][j] <= best * TIE_RATIO + TIE_ABS).slice(0, 4);
if (near.length > 1) tieCandidates[i] = near;
}
const xs=[], ys=[];
RAW.forEach(p=>{ xs.push(p.p_x, p.d_x); ys.push(p.p_y, p.d_y); });
const xMin=Math.min(...xs)-1, xMax=Math.max(...xs)+1;
const yMin=Math.min(...ys)-1, yMax=Math.max(...ys)+1;
sx = (x)=> 30 + (x-xMin)/(xMax-xMin)*370;
sy = (y)=> 30 + (yMax-y)/(yMax-yMin)*460;
updateTopology();
}
// 実効的な親(人間の指定があればそれを優先)
function effParent(i) {
if (userParent[i] !== undefined) return userParent[i];
return gradParent[i];
}
// 実効的な連結種別(容量超過で格下げされていれば直列)
function effType(i, p) {
if (demoted[i]) return 'seq';
return edgeType[i][p];
}
function toggleCut(childId) {
if (userCuts[childId]) delete userCuts[childId];
else userCuts[childId] = true;
updateTopology();
}
function setParent(i, val) {
if (val === '') delete userParent[i];
else userParent[i] = +val;
updateTopology();
}
function toggleRouteDisplay(rootId, isChecked) { visibleRoutes[rootId] = isChecked; drawSVG(); }
function toggleAllRoutes(isChecked) {
Object.keys(visibleRoutes).forEach(r => visibleRoutes[r] = isChecked);
document.querySelectorAll('.route-chk').forEach(chk => chk.checked = isChecked);
drawSVG();
}
/* ===== 修正② 混載チェーンの累積容量チェック =====
nestエッジは2点間だけ見ても足りない。nestで繋がった塊は同時に車上に乗るので、
塊ごとの合計量が車格を超えないかを Union-Find で見る。
超える縁は「切る」のではなく直列(seq)に格下げする——順番に回れば積載は競合しない。
近い(Cが小さい)縁から順に混載を確定させる貪欲法。 */
function resolveNestCapacity(CAPACITY) {
demoted = {};
nestGroupLoad = {};
const uf = [...Array(n).keys()];
const load = RAW.map(r => r.demand);
const find = (x) => { while(uf[x] !== x) { uf[x] = uf[uf[x]]; x = uf[x]; } return x; };
const edges = [];
for(let i=0; i<n; i++){
const p = effParent(i);
if (p === undefined || userCuts[i]) continue;
if (edgeType[i][p] !== 'nest') continue;
edges.push({ i, p, c: C[i][p] });
}
edges.sort((a,b) => a.c - b.c);
for (const e of edges) {
const ri = find(e.i), rp = find(e.p);
if (ri === rp) continue;
if (load[ri] + load[rp] <= CAPACITY) {
uf[ri] = rp;
load[rp] += load[ri];
} else {
demoted[e.i] = true; // 混載できない → 直列でつなぐ
}
}
for(let i=0; i<n; i++) nestGroupLoad[i] = +load[find(i)].toFixed(1);
}
function updateTopology() {
const CAPACITY = currentCapacity();
resolveNestCapacity(CAPACITY);
// 実効親をたどって根(=便)を決める。親は必ず自分より terrain が低いので循環しない。
currentFinalRoot = new Array(n);
for(let j=0; j<n; j++){
let cur = j, guard = 0;
while(effParent(cur) !== undefined && !userCuts[cur] && guard++ < n) {
cur = effParent(cur);
}
currentFinalRoot[j] = cur;
}
let clusters = {};
for(let j=0; j<n; j++){ (clusters[currentFinalRoot[j]] ??= []).push(j); }
currentRootColors = {};
Object.keys(clusters).forEach((r, i) => {
currentRootColors[r] = PALETTE[i % PALETTE.length];
if(visibleRoutes[r] === undefined) visibleRoutes[r] = true;
});
Object.keys(visibleRoutes).forEach(r => { if(!clusters[r]) delete visibleRoutes[r]; });
buildRoutesAndFilters(clusters, currentRootColors, CAPACITY);
drawSVG();
}
function drawSVG() {
svg.innerHTML = '';
svg.appendChild(el('defs',{}));
Object.entries(WARDS).forEach(([name,[x,y]])=>{
svg.appendChild(el('text',{x:sx(x),y:sy(y)-15,class:'ward-label','text-anchor':'middle'})).textContent=name;
});
// 1. 各タスク自身の発→着線(グレー)
for(let i=0; i<n; i++) {
if (!visibleRoutes[currentFinalRoot[i]]) continue;
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[i].d_x), y2:sy(RAW[i].d_y),
stroke: '#bdc3c7', 'stroke-width': 2, opacity: 0.5
}));
}
// 2. 勾配によるつながり線
for(let i=0; i<n; i++){
const p = effParent(i);
if(p === undefined) continue;
if (!visibleRoutes[currentFinalRoot[i]] && !visibleRoutes[currentFinalRoot[p]]) continue;
if (userCuts[i]) {
let cx = (sx(RAW[i].d_x) + sx(RAW[p].p_x))/2;
let cy = (sy(RAW[i].d_y) + sy(RAW[p].p_y))/2;
let cutIcon = el('text', {x:cx, y:cy+4, 'text-anchor':'middle', fill:'#e74c3c', 'font-size':'16px', opacity:0.8});
cutIcon.textContent = '✂️';
svg.appendChild(cutIcon);
continue;
}
if (!visibleRoutes[currentFinalRoot[i]]) continue;
const routeColor = currentRootColors[currentFinalRoot[i]];
const type = effType(i, p);
if (type === 'seq') {
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 2, 'stroke-dasharray': '4,4'
}));
// 容量超過で混載から落ちた縁は、そうと分かるように印を置く
if (demoted[i]) {
let cx = (sx(RAW[i].d_x) + sx(RAW[p].p_x))/2;
let cy = (sy(RAW[i].d_y) + sy(RAW[p].p_y))/2;
let ic = el('text', {x:cx, y:cy+4, 'text-anchor':'middle', fill:'#e67e22', 'font-size':'13px'});
ic.textContent = '⚖';
svg.appendChild(ic);
}
} else {
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].d_x), y2:sy(RAW[p].d_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
}
// 同点が残っている箇所(人間が拾うべき地点)
if (tieCandidates[i] && userParent[i] === undefined) {
let mx = (sx(RAW[i].p_x) + sx(RAW[i].d_x))/2;
let my = (sy(RAW[i].p_y) + sy(RAW[i].d_y))/2;
let ic = el('text', {x:mx, y:my-8, 'text-anchor':'middle', fill:'#e74c3c', 'font-size':'13px'});
ic.textContent = '⚡';
svg.appendChild(ic);
}
}
// 3. 発・着ノード描画
for(let i=0; i<n; i++){
if (!visibleRoutes[currentFinalRoot[i]]) continue;
let r = 5 + RAW[i].demand * 1.5;
let c = currentRootColors[currentFinalRoot[i]];
svg.appendChild(el('circle', { cx:sx(RAW[i].p_x), cy:sy(RAW[i].p_y), r:r, fill:c, stroke:'#fff', 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].p_x), y:sy(RAW[i].p_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '+';
svg.appendChild(el('circle', { cx:sx(RAW[i].d_x), cy:sy(RAW[i].d_y), r:r, fill:c, stroke:'#fff', 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].d_x), y:sy(RAW[i].d_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '-';
}
}
function buildRoutesAndFilters(clusters, rootColors, CAPACITY) {
let dBody = document.getElementById('dispatchBody');
let filterContainer = document.getElementById('routeFilters');
dBody.innerHTML = '';
let filterHtml = '<strong>表示切替</strong>';
filterHtml += `<label class="filter-label" style="margin-bottom:8px;"><input type="checkbox" onchange="toggleAllRoutes(this.checked)" checked> 全て表示</label>`;
let truckId = 1;
let sortedRoots = Object.keys(clusters).sort((a,b) => clusters[b].length - clusters[a].length);
sortedRoots.forEach(r => {
let pts = clusters[r];
pts.sort((a, b) => terrain[b] - terrain[a]);
let routeColor = rootColors[r];
let total = +pts.reduce((s,i)=> s + RAW[i].demand, 0).toFixed(1);
let peak = Math.max(...pts.map(i => nestGroupLoad[i]));
let isChecked = visibleRoutes[r] ? "checked" : "";
filterHtml += `<label class="filter-label">
<input type="checkbox" class="route-chk" value="${r}" onchange="toggleRouteDisplay('${r}', this.checked)" ${isChecked}>
<div class="color-box" style="background:${routeColor}"></div> 第 ${truckId} 便
</label>`;
dBody.innerHTML += `<tr class="truck-header" style="background:${routeColor};">
<td colspan="7">🚚 第 ${truckId++} 便 (${pts.length}件 / 総量 ${total}t / 最大同時積載 ${peak}t ≦ ${CAPACITY}t)</td></tr>`;
dBody.innerHTML += `<tr style="background:#eee; font-size:0.9em;">
<th>ID</th><th>積地</th><th>降地</th><th>量(t)</th><th>同時積載</th><th>状態 / 次の便先</th><th>操作</th></tr>`;
pts.forEach(i => {
const p = effParent(i);
let badge = "", actionBtn = "", parentCell = "-";
if (p !== undefined && !userCuts[i]) {
const t = effType(i, p);
badge = t === 'seq' ? '<span class="badge seq">直列</span>' : '<span class="badge nest">混載</span>';
if (demoted[i]) badge += ' <span class="badge demote">容量で直列化</span>';
actionBtn = `<button class="btn-cut" onclick="toggleCut(${i})">✂️ 分割</button>`;
const cands = tieCandidates[i];
if (cands) {
const opts = cands.map(j =>
`<option value="${j}" ${p===j?'selected':''}>#${RAW[j].id} (${C[i][j].toFixed(2)}${edgeType[i][j]==='nest'?' 混':' 直'})</option>`
).join('');
const cls = (userParent[i] === undefined) ? 'sel-parent tie' : 'sel-parent';
parentCell = `<span class="badge tie">⚡僅差</span><br>
<select class="${cls}" onchange="setParent(${i}, this.value)">${opts}</select>`;
} else {
parentCell = `#${RAW[p].id}`;
}
}
if (userCuts[i]) {
badge = '<span class="badge" style="background:#95a5a6;">切断中</span>';
actionBtn = `<button class="btn-restore" onclick="toggleCut(${i})">🔗 繋ぐ</button>`;
}
const loadCls = nestGroupLoad[i] > CAPACITY ? 'cap-over' : '';
dBody.innerHTML += `<tr>
<td>#${RAW[i].id}</td>
<td>${RAW[i].p_near}</td>
<td>${RAW[i].d_near}</td>
<td>${RAW[i].demand} t</td>
<td class="${loadCls}">${nestGroupLoad[i]} t</td>
<td>${badge}<br>${parentCell}</td>
<td>${actionBtn}</td>
</tr>`;
});
});
filterContainer.innerHTML = filterHtml;
}
generateData();
</script>
</body>
</html>因みにさ、gradもdivも本読んだだけ。
それで十分だと思います。使い方は外していません。
ただ、今のコードでは div が実際には効いていません。terrain の計算が RAW[j].demand を符号なしで足しているので、発(+)も着(−)も同じ重さの「重り」として扱われています。地形は谷しかできない(全部マイナス方向に凹む)状態です。左パネルで+と−を描き分けているのに、高さ場はその区別を見ていない。
div を本当に効かせるなら、符号を入れるだけです。発地に +demand、着地に −demand を置く。そうすると地形に山と谷が両方できて、勾配降下が「余っているところから足りないところへ流す」という意味になります。荷物が動く理由そのものが地形に乗る。琵琶湖疏水のフレームで言えば、今の版は水源の標高だけ見ていて、放水先の標高を見ていない状態です。
そして grad と div を続けて掛けるとラプラシアンになります。∇²φ = −ρ、つまり湧き出し・吸い込みの分布 ρ から電位 φ を求めるポアソン方程式です。実は KDE のガウス核はこのグリーン関数の近似なので、本を読んだだけの直感で既にその隣に立っています。厳密にやるなら「地形を作って降りる」ではなく「ポアソンを解いて降りる」になる、というだけの違いです。
補足として一言だけ。グラフ上の Hodge 分解(離散ホッジ・HodgeRank)を見ておくと後で効くと思います。任意の流れが「勾配成分+循環成分+調和成分」に一意分解する定理で、配車で言えば勾配成分=必要な輸送、循環成分=ぐるぐる回っている無駄、になります。無駄を定量化する道具が欲しくなったとき、ここに戻ってくることになるはずです。
符号付きの terrain に差し替えた版を作りますか。20行程度の変更で、山と谷の両方が出る地形になります。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>配車シミュレーター rev.3(符号付きポテンシャル場)</title>
<style>
:root { --bg-dark: #0B1420; --line-dark: #1C2E3F; --text-dark: #E7EDF3; }
body { font-family: sans-serif; margin: 0; padding: 10px 15px; background-color: #f0f2f5; display: flex; flex-direction: column; height: 100vh; box-sizing: border-box;}
h2 { font-size: 1.1em; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-top: 0; }
.tabs { display: flex; gap: 5px; margin-bottom: 10px; border-bottom: 2px solid #3498db; padding-bottom: 0; }
.tab-btn { background: #ecf0f1; border: 1px solid #bdc3c7; border-bottom: none; color: #7f8c8d; padding: 8px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: bold; width: auto; font-size: 0.9em;}
.tab-btn:hover { background: #e0e6ed; }
.tab-btn.active { background: #3498db; color: #fff; border-color: #3498db; }
.layout-container { display: flex; gap: 15px; flex: 1; overflow: hidden; }
.panel { background: #fff; border-radius: 8px; padding: 15px; display: flex; flex-direction: column; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.panel-left { flex: 1.2; overflow-y: auto; }
.panel-center { flex: 1.5; background: #fafafa; overflow-y: auto; display: flex; flex-direction: column;}
.panel-right { flex: 2.0; overflow-y: auto; }
.layout-container.map-only .panel-left { display: none; }
.layout-container.map-only .panel-right { display: none; }
.layout-container.map-only .panel-center { flex: 1; }
button { background: #3498db; color: #fff; border: none; padding: 10px; border-radius: 4px; cursor: pointer; width: 100%; font-weight: bold; }
button:hover { background: #2980b9; }
table { width: 100%; border-collapse: collapse; font-size: 0.85em; margin-bottom: 10px; }
th, td { border: 1px solid #ddd; padding: 5px; text-align: center; }
th { background-color: #ecf0f1; position: sticky; top: 0; }
.svg-wrapper { flex: 1; background: var(--bg-dark); border-radius: 8px; position: relative; min-height: 400px; border: 1px solid var(--line-dark); overflow: hidden;}
svg { width: 100%; height: 100%; display: block; cursor: grab;}
svg:active { cursor: grabbing; }
.ward-label { fill: #8FA3B8; font-size: 10px; font-weight: bold; pointer-events: none; }
.truck-header { color: #fff; font-weight: bold; }
.badge { padding: 3px 6px; border-radius: 3px; font-size: 0.8em; color: #fff; display: inline-block;}
.badge.seq { background: #3498db; }
.badge.nest { background: #9b59b6; }
.badge.demote { background: #e67e22; }
.badge.tie { background: #c0392b; }
.badge.uphill { background: #c0392b; }
.btn-cut { background: #e74c3c; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-cut:hover { background: #c0392b; }
.btn-restore { background: #7f8c8d; padding: 4px 8px; font-size: 0.8em; border-radius: 4px; border: none; color: white; cursor: pointer; width: auto;}
.btn-restore:hover { background: #95a5a6; }
.sel-parent { font-size: 0.85em; max-width: 110px; }
.sel-parent.tie { border: 2px solid #c0392b; background: #fdf2f0; }
.cap-note { font-size: 0.85em; color: #7f8c8d; }
.cap-over { color: #c0392b; font-weight: bold; }
.drop-neg { color: #c0392b; font-weight: bold; }
.drop-pos { color: #16a085; }
.map-controls { position: absolute; top: 10px; right: 10px; display: flex; gap: 5px; z-index: 10; }
.map-controls button { background: rgba(255,255,255,0.9); color: #2c3e50; border: 1px solid #bdc3c7; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; width: auto; font-size: 14px;}
.map-controls button:hover { background: #ecf0f1; }
.route-filters { position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.92); border: 1px solid #bdc3c7; border-radius: 6px; padding: 10px; z-index: 10; display: flex; flex-direction: column; gap: 5px; font-size: 13px; max-height: 80%; overflow-y: auto; box-shadow: 0 2px 6px rgba(0,0,0,0.15);}
.route-filters strong { color: #2c3e50; margin-bottom: 5px; display: block; border-bottom: 1px solid #ddd; padding-bottom: 4px; }
.filter-label { display: flex; align-items: center; gap: 6px; cursor: pointer; color: #333; }
.color-box { width: 14px; height: 14px; border-radius: 3px; }
.legend-swatch { width: 60px; height: 10px; border-radius: 2px; background: linear-gradient(to right, #2980b9, #16324a, #d35400); }
</style>
</head>
<body>
<div class="tabs">
<button class="tab-btn active" id="tab-normal" onclick="switchView('normal')">📊 通常ビュー (操作・分割)</button>
<button class="tab-btn" id="tab-map" onclick="switchView('map-only')">🗺️ マップ全面 (ルート確認)</button>
</div>
<div class="layout-container" id="mainLayout">
<div class="panel panel-left">
<h2>1. 配送ペア設定</h2>
<div style="margin-bottom:15px; font-size:0.9em;">
<label>配車ベース車格:
<select id="capSelect" onchange="recompute()">
<option value="4">4t</option>
<option value="8" selected>8t</option>
<option value="13">13t</option>
</select>
</label>
<br>
<span class="cap-note">※車格を変えても荷物セットは保持され、混載判定だけが引き直されます</span>
<button style="margin-top:10px;" onclick="generateData()">🎲 データを再生成</button>
</div>
<table>
<thead><tr><th>ID</th><th>品名</th><th>発 +</th><th>着 -</th><th>量(t)</th></tr></thead>
<tbody id="initialBody"></tbody>
</table>
</div>
<div class="panel panel-center">
<h2>2. マップ (ルート確認)</h2>
<div class="svg-wrapper" id="svgWrap">
<div id="routeFilters" class="route-filters"></div>
<div class="map-controls">
<button onclick="zoomMap(0.8)" title="拡大">+</button>
<button onclick="zoomMap(1.25)" title="縮小">-</button>
<button onclick="resetMap()" title="初期表示に戻す">リセット</button>
</div>
<svg id="mapSvg" viewBox="0 0 430 520" preserveAspectRatio="xMidYMid meet"></svg>
</div>
</div>
<div class="panel panel-right">
<h2>3. 実行ルート (手動調整)</h2>
<table id="dispatchTable">
<tbody id="dispatchBody"><tr><td>計算結果がここに表示されます</td></tr></tbody>
</table>
</div>
</div>
<script>
const WARDS = {"千代田":[0.5,-0.5],"中央":[2.0,-1.0],"港":[0.0,-4.5],"新宿":[-6.0,0.5],"文京":[-1.0,3.5],"豊島":[-5.0,5.5]};
const productTypes = ["食料", "飲料", "建材", "雑貨", "家電"];
const PALETTE = ["#3498db", "#e67e22", "#2ecc71", "#9b59b6", "#f1c40f", "#1abc9c", "#e74c3c", "#34495e"];
const svgNS="http://www.w3.org/2000/svg";
function el(tag, attrs){ const e=document.createElementNS(svgNS,tag); for(const k in attrs) e.setAttribute(k, attrs[k]); return e; }
const BANDWIDTH = 3.0;
const TIE_RATIO = 1.08;
const TIE_ABS = 0.30;
let RAW = [], n = 0, C, edgeType, gradParent;
let terrain, phiP, phiD, drop; // 符号付きポテンシャルと落差
let tieCandidates = {};
let userCuts = {}, userParent = {}, demoted = {}, nestGroupLoad = {};
let sx, sy, invX, invY;
let fieldCells = [], fieldMax = 1, showField = true;
let visibleRoutes = {}, currentFinalRoot = [], currentRootColors = {};
// --- マップのズーム・パンスクロール制御 ---
const svg = document.getElementById('mapSvg');
const DEFAULT_VB = { x: 0, y: 0, w: 430, h: 520 };
let vb = { ...DEFAULT_VB };
let isDown = false, startX, startY;
function updateViewBox() { svg.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`); }
function resetMap() { vb = { ...DEFAULT_VB }; updateViewBox(); }
function zoomMap(factor) {
let cx = vb.x + vb.w / 2, cy = vb.y + vb.h / 2;
vb.w *= factor; vb.h *= factor;
vb.x = cx - vb.w / 2; vb.y = cy - vb.h / 2;
updateViewBox();
}
svg.addEventListener('mousedown', (e) => { isDown = true; startX = e.clientX; startY = e.clientY; });
window.addEventListener('mouseup', () => { isDown = false; });
window.addEventListener('mousemove', (e) => {
if (!isDown) return;
e.preventDefault();
let rect = svg.getBoundingClientRect();
vb.x -= (e.clientX - startX) * (vb.w / rect.width);
vb.y -= (e.clientY - startY) * (vb.h / rect.height);
updateViewBox();
startX = e.clientX; startY = e.clientY;
});
svg.addEventListener('wheel', (e) => {
e.preventDefault();
let rect = svg.getBoundingClientRect();
let mouseX = vb.x + (e.clientX - rect.left) * (vb.w / rect.width);
let mouseY = vb.y + (e.clientY - rect.top) * (vb.h / rect.height);
let zoomFactor = e.deltaY > 0 ? 1.1 : 0.9;
vb.w *= zoomFactor; vb.h *= zoomFactor;
vb.x = mouseX - (e.clientX - rect.left) * (vb.w / rect.width);
vb.y = mouseY - (e.clientY - rect.top) * (vb.h / rect.height);
updateViewBox();
}, { passive: false });
function switchView(mode) {
const layout = document.getElementById('mainLayout');
const tabNormal = document.getElementById('tab-normal');
const tabMap = document.getElementById('tab-map');
if (mode === 'map-only') {
layout.classList.add('map-only');
tabMap.classList.add('active'); tabNormal.classList.remove('active');
} else {
layout.classList.remove('map-only');
tabNormal.classList.add('active'); tabMap.classList.remove('active');
}
setTimeout(updateViewBox, 50);
}
function currentCapacity() { return +document.getElementById('capSelect').value; }
function generateData() {
const CAPACITY = currentCapacity();
const pts = []; let id = 0;
const wNames = Object.keys(WARDS);
for(let i=0; i<15; i++) {
let pw = wNames[Math.floor(Math.random()*wNames.length)];
let dw = wNames[Math.floor(Math.random()*wNames.length)];
if(pw === dw) dw = wNames[(wNames.indexOf(dw)+1)%wNames.length];
pts.push({
id: id++, name: productTypes[Math.floor(Math.random()*productTypes.length)],
p_near: pw, p_x: WARDS[pw][0] + (Math.random()*2-1), p_y: WARDS[pw][1] + (Math.random()*2-1),
d_near: dw, d_x: WARDS[dw][0] + (Math.random()*2-1), d_y: WARDS[dw][1] + (Math.random()*2-1),
demand: +(CAPACITY * (0.2 + Math.random()*0.7)).toFixed(1)
});
}
RAW = pts;
userCuts = {}; userParent = {}; visibleRoutes = {};
resetMap();
renderLeftTable();
recompute();
}
function recompute() {
if (RAW.length === 0) { generateData(); return; }
userParent = {};
computePairGradient(currentCapacity());
}
function renderLeftTable() {
const tb = document.getElementById('initialBody');
tb.innerHTML = '';
RAW.forEach(p => {
tb.innerHTML += `<tr><td>#${p.id}</td><td>${p.name}</td><td>${p.p_near}</td><td>${p.d_near}</td><td>${p.demand}</td></tr>`;
});
}
/* ===== 符号付きポテンシャル場 =====
発地は湧き出し(+demand)、着地は吸い込み(−demand)。
従来版は両方を同じ重りとして足していたため谷しかできなかった。
符号を入れると山(荷が余る所)と谷(荷が要る所)が両方立ち、
勾配を降りることが「余剰から不足へ流す」という意味になる。 */
function potentialAt(x, y) {
let phi = 0;
for (let k = 0; k < n; k++) {
phi += RAW[k].demand * Math.exp(-Math.hypot(x - RAW[k].p_x, y - RAW[k].p_y) / BANDWIDTH);
phi -= RAW[k].demand * Math.exp(-Math.hypot(x - RAW[k].d_x, y - RAW[k].d_y) / BANDWIDTH);
}
return phi;
}
function computePairGradient(CAPACITY) {
n = RAW.length;
C = Array.from({length:n}, ()=>new Array(n).fill(Infinity));
edgeType = Array.from({length:n}, ()=>new Array(n).fill(''));
for(let i=0; i<n; i++){
for(let j=0; j<n; j++){
if(i===j) continue;
let seqDist = Math.hypot(RAW[i].d_x - RAW[j].p_x, RAW[i].d_y - RAW[j].p_y);
let nestDist = Infinity;
if (RAW[i].demand + RAW[j].demand <= CAPACITY) {
nestDist = Math.hypot(RAW[i].p_x - RAW[j].p_x, RAW[i].p_y - RAW[j].p_y) +
Math.hypot(RAW[i].d_x - RAW[j].d_x, RAW[i].d_y - RAW[j].d_y) + 1.0;
}
if(seqDist <= nestDist) { C[i][j] = seqDist; edgeType[i][j] = 'seq'; }
else { C[i][j] = nestDist; edgeType[i][j] = 'nest'; }
}
}
// 各タスクの高さは「荷を降ろし終えた地点のポテンシャル」。
// そこから次の便先へ降りる。落差 drop = φ(発) − φ(着) はその荷自身が均した量。
phiP = RAW.map(r => potentialAt(r.p_x, r.p_y));
phiD = RAW.map(r => potentialAt(r.d_x, r.d_y));
terrain = phiD.slice();
drop = RAW.map((_, i) => phiP[i] - phiD[i]);
gradParent = {};
tieCandidates = {};
for(let i=0; i<n; i++){
let lower = [...Array(n).keys()].filter(j => terrain[j] < terrain[i] && isFinite(C[i][j]));
if(lower.length === 0) continue;
lower.sort((a,b) => C[i][a] - C[i][b]);
gradParent[i] = lower[0];
const best = C[i][lower[0]];
const near = lower.filter(j => C[i][j] <= best * TIE_RATIO + TIE_ABS).slice(0, 4);
if (near.length > 1) tieCandidates[i] = near;
}
const xs=[], ys=[];
RAW.forEach(p=>{ xs.push(p.p_x, p.d_x); ys.push(p.p_y, p.d_y); });
const xMin=Math.min(...xs)-1, xMax=Math.max(...xs)+1;
const yMin=Math.min(...ys)-1, yMax=Math.max(...ys)+1;
sx = (x)=> 30 + (x-xMin)/(xMax-xMin)*370;
sy = (y)=> 30 + (yMax-y)/(yMax-yMin)*460;
invX = (px)=> xMin + (px-30)/370*(xMax-xMin);
invY = (py)=> yMax - (py-30)/460*(yMax-yMin);
buildFieldGrid();
updateTopology();
}
// 地形をSVG背景に敷くための粗いグリッドを一度だけ焼く
function buildFieldGrid() {
const STEP = 14;
fieldCells = []; fieldMax = 1e-6;
for (let px = 0; px < 430; px += STEP) {
for (let py = 0; py < 520; py += STEP) {
const v = potentialAt(invX(px + STEP/2), invY(py + STEP/2));
fieldCells.push({ px, py, v });
if (Math.abs(v) > fieldMax) fieldMax = Math.abs(v);
}
}
}
function fieldColor(v) {
const t = v / fieldMax; // -1(谷) .. +1(山)
const a = 0.10 + 0.55 * Math.min(1, Math.abs(t));
return t >= 0 ? `rgba(211,84,0,${a.toFixed(3)})` // 山=荷が余る側
: `rgba(41,128,185,${a.toFixed(3)})`; // 谷=荷が要る側
}
function effParent(i) { return userParent[i] !== undefined ? userParent[i] : gradParent[i]; }
function effType(i, p) { return demoted[i] ? 'seq' : edgeType[i][p]; }
function toggleCut(childId) {
if (userCuts[childId]) delete userCuts[childId]; else userCuts[childId] = true;
updateTopology();
}
function setParent(i, val) {
if (val === '') delete userParent[i]; else userParent[i] = +val;
updateTopology();
}
function toggleRouteDisplay(rootId, isChecked) { visibleRoutes[rootId] = isChecked; drawSVG(); }
function toggleAllRoutes(isChecked) {
Object.keys(visibleRoutes).forEach(r => visibleRoutes[r] = isChecked);
document.querySelectorAll('.route-chk').forEach(chk => chk.checked = isChecked);
drawSVG();
}
function toggleField(isChecked) { showField = isChecked; drawSVG(); }
// nest鎖の累積容量チェック(Union-Find、超過分は直列へ格下げ)
function resolveNestCapacity(CAPACITY) {
demoted = {}; nestGroupLoad = {};
const uf = [...Array(n).keys()];
const load = RAW.map(r => r.demand);
const find = (x) => { while(uf[x] !== x) { uf[x] = uf[uf[x]]; x = uf[x]; } return x; };
const edges = [];
for(let i=0; i<n; i++){
const p = effParent(i);
if (p === undefined || userCuts[i]) continue;
if (edgeType[i][p] !== 'nest') continue;
edges.push({ i, p, c: C[i][p] });
}
edges.sort((a,b) => a.c - b.c);
for (const e of edges) {
const ri = find(e.i), rp = find(e.p);
if (ri === rp) continue;
if (load[ri] + load[rp] <= CAPACITY) { uf[ri] = rp; load[rp] += load[ri]; }
else { demoted[e.i] = true; }
}
for(let i=0; i<n; i++) nestGroupLoad[i] = +load[find(i)].toFixed(1);
}
function updateTopology() {
const CAPACITY = currentCapacity();
resolveNestCapacity(CAPACITY);
currentFinalRoot = new Array(n);
for(let j=0; j<n; j++){
let cur = j, guard = 0;
while(effParent(cur) !== undefined && !userCuts[cur] && guard++ < n) cur = effParent(cur);
currentFinalRoot[j] = cur;
}
let clusters = {};
for(let j=0; j<n; j++){ (clusters[currentFinalRoot[j]] ??= []).push(j); }
currentRootColors = {};
Object.keys(clusters).forEach((r, i) => {
currentRootColors[r] = PALETTE[i % PALETTE.length];
if(visibleRoutes[r] === undefined) visibleRoutes[r] = true;
});
Object.keys(visibleRoutes).forEach(r => { if(!clusters[r]) delete visibleRoutes[r]; });
buildRoutesAndFilters(clusters, currentRootColors, CAPACITY);
drawSVG();
}
function drawSVG() {
svg.innerHTML = '';
svg.appendChild(el('defs',{}));
// 0. 背景の地形
if (showField) {
const g = el('g', { 'pointer-events': 'none' });
fieldCells.forEach(c => {
g.appendChild(el('rect', { x:c.px, y:c.py, width:15, height:15, fill: fieldColor(c.v) }));
});
svg.appendChild(g);
}
Object.entries(WARDS).forEach(([name,[x,y]])=>{
svg.appendChild(el('text',{x:sx(x),y:sy(y)-15,class:'ward-label','text-anchor':'middle'})).textContent=name;
});
// 1. 各タスク自身の発→着線
for(let i=0; i<n; i++) {
if (!visibleRoutes[currentFinalRoot[i]]) continue;
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[i].d_x), y2:sy(RAW[i].d_y),
stroke: '#dfe6e9', 'stroke-width': 2, opacity: 0.45
}));
}
// 2. 勾配によるつながり線
for(let i=0; i<n; i++){
const p = effParent(i);
if(p === undefined) continue;
if (!visibleRoutes[currentFinalRoot[i]] && !visibleRoutes[currentFinalRoot[p]]) continue;
if (userCuts[i]) {
let cx = (sx(RAW[i].d_x) + sx(RAW[p].p_x))/2;
let cy = (sy(RAW[i].d_y) + sy(RAW[p].p_y))/2;
let cutIcon = el('text', {x:cx, y:cy+4, 'text-anchor':'middle', fill:'#e74c3c', 'font-size':'16px', opacity:0.9});
cutIcon.textContent = '✂️';
svg.appendChild(cutIcon);
continue;
}
if (!visibleRoutes[currentFinalRoot[i]]) continue;
const routeColor = currentRootColors[currentFinalRoot[i]];
const type = effType(i, p);
if (type === 'seq') {
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 2, 'stroke-dasharray': '4,4'
}));
if (demoted[i]) {
let cx = (sx(RAW[i].d_x) + sx(RAW[p].p_x))/2;
let cy = (sy(RAW[i].d_y) + sy(RAW[p].p_y))/2;
let ic = el('text', {x:cx, y:cy+4, 'text-anchor':'middle', fill:'#f39c12', 'font-size':'13px'});
ic.textContent = '⚖';
svg.appendChild(ic);
}
} else {
svg.appendChild(el('line', {
x1:sx(RAW[i].p_x), y1:sy(RAW[i].p_y), x2:sx(RAW[p].p_x), y2:sy(RAW[p].p_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
svg.appendChild(el('line', {
x1:sx(RAW[i].d_x), y1:sy(RAW[i].d_y), x2:sx(RAW[p].d_x), y2:sy(RAW[p].d_y),
stroke: routeColor, 'stroke-width': 3, 'stroke-dasharray': '2,3'
}));
}
if (tieCandidates[i] && userParent[i] === undefined) {
let mx = (sx(RAW[i].p_x) + sx(RAW[i].d_x))/2;
let my = (sy(RAW[i].p_y) + sy(RAW[i].d_y))/2;
let ic = el('text', {x:mx, y:my-8, 'text-anchor':'middle', fill:'#e74c3c', 'font-size':'13px'});
ic.textContent = '⚡';
svg.appendChild(ic);
}
}
// 3. 発・着ノード
for(let i=0; i<n; i++){
if (!visibleRoutes[currentFinalRoot[i]]) continue;
let r = 5 + RAW[i].demand * 1.5;
let c = currentRootColors[currentFinalRoot[i]];
svg.appendChild(el('circle', { cx:sx(RAW[i].p_x), cy:sy(RAW[i].p_y), r:r, fill:c, stroke:'#fff', 'stroke-width':1.5, 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].p_x), y:sy(RAW[i].p_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '+';
svg.appendChild(el('circle', { cx:sx(RAW[i].d_x), cy:sy(RAW[i].d_y), r:r, fill:c, stroke:'#fff', 'stroke-width':1.5, 'pointer-events': 'none'}));
svg.appendChild(el('text', {x:sx(RAW[i].d_x), y:sy(RAW[i].d_y)+3, 'text-anchor':'middle', fill:'#fff', 'font-size':'10px', 'pointer-events': 'none'})).textContent = '-';
}
}
function buildRoutesAndFilters(clusters, rootColors, CAPACITY) {
let dBody = document.getElementById('dispatchBody');
let filterContainer = document.getElementById('routeFilters');
dBody.innerHTML = '';
let filterHtml = '<strong>表示切替</strong>';
filterHtml += `<label class="filter-label"><input type="checkbox" onchange="toggleField(this.checked)" ${showField?'checked':''}> 地形を表示</label>`;
filterHtml += `<div class="filter-label" style="margin-bottom:8px; font-size:11px; color:#555;">
<span>谷</span><div class="legend-swatch"></div><span>山</span></div>`;
filterHtml += `<label class="filter-label" style="margin-bottom:8px;"><input type="checkbox" onchange="toggleAllRoutes(this.checked)" checked> 全て表示</label>`;
let truckId = 1;
let sortedRoots = Object.keys(clusters).sort((a,b) => clusters[b].length - clusters[a].length);
sortedRoots.forEach(r => {
let pts = clusters[r];
pts.sort((a, b) => terrain[b] - terrain[a]);
let routeColor = rootColors[r];
let total = +pts.reduce((s,i)=> s + RAW[i].demand, 0).toFixed(1);
let peak = Math.max(...pts.map(i => nestGroupLoad[i]));
let netDrop = +pts.reduce((s,i)=> s + drop[i], 0).toFixed(2);
let isChecked = visibleRoutes[r] ? "checked" : "";
filterHtml += `<label class="filter-label">
<input type="checkbox" class="route-chk" value="${r}" onchange="toggleRouteDisplay('${r}', this.checked)" ${isChecked}>
<div class="color-box" style="background:${routeColor}"></div> 第 ${truckId} 便
</label>`;
dBody.innerHTML += `<tr class="truck-header" style="background:${routeColor};">
<td colspan="8">🚚 第 ${truckId++} 便 (${pts.length}件 / 総量 ${total}t / 最大同時積載 ${peak}t ≦ ${CAPACITY}t / 便の総落差 ${netDrop})</td></tr>`;
dBody.innerHTML += `<tr style="background:#eee; font-size:0.9em;">
<th>ID</th><th>積地</th><th>降地</th><th>量(t)</th><th>同時積載</th><th>落差</th><th>状態 / 次の便先</th><th>操作</th></tr>`;
pts.forEach(i => {
const p = effParent(i);
let badge = "", actionBtn = "", parentCell = "-(終点)";
if (p !== undefined && !userCuts[i]) {
const t = effType(i, p);
badge = t === 'seq' ? '<span class="badge seq">直列</span>' : '<span class="badge nest">混載</span>';
if (demoted[i]) badge += ' <span class="badge demote">容量で直列化</span>';
actionBtn = `<button class="btn-cut" onclick="toggleCut(${i})">✂️ 分割</button>`;
const cands = tieCandidates[i];
if (cands) {
const opts = cands.map(j =>
`<option value="${j}" ${p===j?'selected':''}>#${RAW[j].id} (${C[i][j].toFixed(2)}${edgeType[i][j]==='nest'?' 混':' 直'})</option>`
).join('');
const cls = (userParent[i] === undefined) ? 'sel-parent tie' : 'sel-parent';
parentCell = `<span class="badge tie">⚡僅差</span><br>
<select class="${cls}" onchange="setParent(${i}, this.value)">${opts}</select>`;
} else {
parentCell = `#${RAW[p].id}`;
}
}
if (userCuts[i]) {
badge = '<span class="badge" style="background:#95a5a6;">切断中</span>';
actionBtn = `<button class="btn-restore" onclick="toggleCut(${i})">🔗 繋ぐ</button>`;
}
const loadCls = nestGroupLoad[i] > CAPACITY ? 'cap-over' : '';
const d = drop[i];
const dropCell = d < 0
? `<span class="drop-neg">${d.toFixed(2)}</span><br><span class="badge uphill">逆流</span>`
: `<span class="drop-pos">${d.toFixed(2)}</span>`;
dBody.innerHTML += `<tr>
<td>#${RAW[i].id}</td>
<td>${RAW[i].p_near}</td>
<td>${RAW[i].d_near}</td>
<td>${RAW[i].demand} t</td>
<td class="${loadCls}">${nestGroupLoad[i]} t</td>
<td>${dropCell}</td>
<td>${badge}<br>${parentCell}</td>
<td>${actionBtn}</td>
</tr>`;
});
});
filterContainer.innerHTML = filterHtml;
}
generateData();
</script>
</body>
</html>