Repository navigation
Expand file tree
/
Copy pathinteractive-projection-pursuit-3d-if.html
More file actions
404 lines (356 loc) · 23.4 KB
/
Copy pathinteractive-projection-pursuit-3d-if.html
File metadata and controls
404 lines (356 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Interactive Projection Pursuit (3D Individual Features)</title>
<!-- Replaced D3 3D rendering with Plotly 3D scatter -->
<script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
<style>
body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;margin:0;padding:20px;background:#f8f9fa}
.container{max-width:1800px;margin:0 auto;background:#fff;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);padding:30px}
.header{text-align:center;margin-bottom:20px}
.header h1{color:#2c3e50;margin-bottom:6px;font-size:1.8em}
.subtitle{color:#7f8c8d;font-size:1.0em}
.controls{display:flex;flex-wrap:wrap;gap:16px;margin-bottom:20px;padding:16px;background:#f8f9fa;border-radius:8px;align-items:flex-start;justify-content:center}
.control-group{display:flex;flex-direction:column;gap:6px;min-width:200px;align-items:flex-start}
.axis-section{background:#fff;border:1px solid #ddd;border-radius:6px;padding:12px;min-width:300px;max-width:420px}
.axis-section h4{margin:0 0 8px 0;color:#2c3e50;text-align:center}
.feature-list{max-height:180px;overflow-y:auto;border:1px solid #e0e0e0;border-radius:4px;padding:8px;background:#fafafa}
.feature-item{display:flex;align-items:center;gap:8px;margin-bottom:6px;padding:4px;border-radius:3px;background:#fff;border:1px solid #e0e0e0}
.feature-item select{flex:1;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px}
.feature-item input[type="number"]{width:60px;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px}
.feature-item .function-select{width:100px;padding:4px 6px;border:1px solid #ccc;border-radius:3px;font-size:12px}
.feature-item button{background:#e74c3c;color:#fff;border:none;border-radius:3px;width:24px;height:24px;cursor:pointer;font-size:12px}
.add-feature-btn{background:#27ae60;color:#fff;border:none;padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px;margin-top:8px;width:100%}
.display-controls{display:flex;flex-direction:column;gap:10px;background:#fff;border:1px solid #ddd;border-radius:6px;padding:12px;min-width:220px}
.chart-container{display:flex;gap:20px;align-items:flex-start}
.chart-area{flex:1;min-height:600px}
.legend-area{width:320px;background:#f8f9fa;border-radius:8px;padding:16px}
.legend-title{font-weight:700;font-size:1.05em;margin-bottom:12px;color:#2c3e50;border-bottom:2px solid #3498db;padding-bottom:6px}
.legend-item{display:flex;align-items:center;margin-bottom:8px;font-size:.9em}
.legend-color{width:16px;height:16px;border-radius:3px;margin-right:8px;border:1px solid #ddd}
.stats-info{margin-top:12px;padding:12px;background:#fff;border-radius:5px;font-size:.9em;color:#495057}
.axis-title{font-size:14px;font-weight:700;fill:#2c3e50}
.grid line{stroke:#e0e0e0;stroke-dasharray:2,2}.grid path{stroke:none}
.x-axis .domain,.y-axis .domain{stroke:#2c3e50;stroke-width:1px}
.point{cursor:pointer;transition:opacity .2s}
.loading-message{text-align:center;padding:60px;color:#666;font-size:16px}
/* Tooltip removed (Plotly provides hover labels) */
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Interactive Multi-Feature Scatter (3D Individual Weights)</h1>
<div class="subtitle">Choose features with +1/-1 weights for X, Y and Z axes. Use mouse to rotate the 3D view.</div>
</div>
<div class="controls">
<div class="control-group">
<label for="file-loader">Load JSON Data:</label>
<input type="file" id="file-loader" accept=".json"/>
<span id="file-status" class="file-status">No file selected</span>
</div>
<div class="axis-section">
<h4>X-Axis Features</h4>
<div id="x-features-list" class="feature-list"></div>
<button id="add-x-feature" class="add-feature-btn">+ Add X Feature</button>
</div>
<div class="axis-section">
<h4>Y-Axis Features</h4>
<div id="y-features-list" class="feature-list"></div>
<button id="add-y-feature" class="add-feature-btn">+ Add Y Feature</button>
</div>
<div class="axis-section">
<h4>Z-Axis Features</h4>
<div id="z-features-list" class="feature-list"></div>
<button id="add-z-feature" class="add-feature-btn">+ Add Z Feature</button>
</div>
<div class="display-controls">
<h4>Display Options</h4>
<div class="control-group">
<label for="point-size">Point Size:</label>
<select id="point-size">
<option value="small">Small</option>
<option value="medium" selected>Medium</option>
<option value="large">Large</option>
</select>
</div>
<div class="control-group">
<label for="point-opacity">Point Opacity:</label>
<select id="point-opacity">
<option value="0.3">30%</option>
<option value="0.5">50%</option>
<option value="0.7" selected>70%</option>
<option value="0.9">90%</option>
</select>
</div>
<div class="control-group">
<label for="show-normal">Show Normal Traffic:</label>
<input type="checkbox" id="show-normal" checked/>
</div>
<div class="control-group">
<label for="lock-scale">Lock Axis Scale:</label>
<input type="checkbox" id="lock-scale" />
</div>
<div class="control-group">
<label> </label>
<button id="export-csv" class="add-feature-btn" style="background:#3498db">Export Transformed CSV</button>
</div>
<div class="control-group">
<label> </label>
<button id="reset-view" class="add-feature-btn" style="background:#6c5ce7">Reset View</button>
</div>
</div>
</div>
<div class="chart-container">
<div class="chart-area">
<div id="chart">
<div class="loading-message">
<h3>Interactive Multi-Feature 3D Scatter Plot</h3>
<p>Please select a JSON file generated by your exporter.</p>
</div>
</div>
</div>
<div class="legend-area">
<div class="legend-title">Attack Classes</div>
<div id="legend"></div>
<div class="stats-info">
<div><strong>Total Points:</strong> <span id="total-points">-</span></div>
<div><strong>Original Dataset:</strong> <span id="original-points">-</span></div>
<div><strong>Sample Rate:</strong> <span id="sample-rate">-</span></div>
<div><strong>Visible Points:</strong> <span id="visible-points">-</span></div>
<div><strong>Features Available:</strong> <span id="feature-count">-</span></div>
<div><strong>Attack Classes:</strong> <span id="attack-classes">-</span></div>
</div>
</div>
</div>
</div>
<script>
// ===== State =====
let currentData = null; // full JSON
let processedData = null; // data.data_points
let xFeatures = [];
let yFeatures = [];
let zFeatures = [];
// No external tooltip needed; Plotly handles hover labels
let axisLock = false;
let lockedB = null; // bounds for x,y,z when locked
// Chart dims
const margin = {top:20, right:20, bottom:20, left:20};
const width = 1000;
const height = 700;
document.addEventListener('DOMContentLoaded', () => {
addFeatureItem('x'); addFeatureItem('y'); addFeatureItem('z');
document.getElementById('file-loader').addEventListener('change', handleFileLoad);
document.getElementById('add-x-feature').addEventListener('click', () => addFeatureItem('x'));
document.getElementById('add-y-feature').addEventListener('click', () => addFeatureItem('y'));
document.getElementById('add-z-feature').addEventListener('click', () => addFeatureItem('z'));
document.getElementById('point-size').addEventListener('change', updateChart);
document.getElementById('point-opacity').addEventListener('change', updateChart);
document.getElementById('show-normal').addEventListener('change', updateChart);
document.getElementById('export-csv').addEventListener('click', exportTransformedCSV);
document.getElementById('lock-scale').addEventListener('change', (e) => { axisLock = e.target.checked; if (axisLock) lockedB = null; updateChart(); });
// Always bind Reset View button
const resetBtn = document.getElementById('reset-view');
if (resetBtn) {
resetBtn.addEventListener('click', () => {
mouse.angleX = DEFAULTS.angleX;
mouse.angleY = DEFAULTS.angleY;
mouse.angleZ = DEFAULTS.angleZ;
pan.x = DEFAULTS.panX;
pan.y = DEFAULTS.panY;
zoom = DEFAULTS.zoom;
updateChart();
});
}
});
// ===== UI builders =====
function addFeatureItem(axis, featureData) {
const list = document.getElementById(`${axis}-features-list`);
const itemId = `${axis}-feature-${Date.now()}-${Math.random().toString(36).slice(2,9)}`;
const item = document.createElement('div');
item.className = 'feature-item';
item.id = itemId;
const sel = document.createElement('select');
sel.className = 'feature-select';
sel.innerHTML = '<option value="">Select feature...</option>';
if (currentData?.metadata?.features) {
currentData.metadata.features.forEach(f => {
const opt = document.createElement('option'); opt.value = f; opt.textContent = f;
if (featureData?.feature === f) opt.selected = true; sel.appendChild(opt);
});
}
const inp = document.createElement('input'); inp.type = 'number'; inp.min='-1'; inp.max='1'; inp.step='2'; inp.value = featureData?.weight ?? '1';
const funcSel = document.createElement('select'); funcSel.className='function-select'; funcSel.innerHTML = `\
<option value="linear">Linear</option>\
<option value="square">Square (x²)</option>\
<option value="sqrt">Square Root (√x)</option>\
<option value="log10">Log10 (log₁₀(x))</option>\
<option value="natural_log">Natural Log (ln(x))</option>\
<option value="inverse">Inverse (1/x)</option>\
<option value="logit">Logit</option>\
<option value="sigmoid">Sigmoid</option>\
`; if (featureData?.function) funcSel.value = featureData.function;
const rm = document.createElement('button'); rm.textContent='×'; rm.title='Remove feature'; rm.onclick = () => { list.removeChild(item); if (axis==='x') xFeatures = xFeatures.filter(f=>f.id!==itemId); else if (axis==='y') yFeatures = yFeatures.filter(f=>f.id!==itemId); else zFeatures = zFeatures.filter(f=>f.id!==itemId); updateChart(); };
sel.addEventListener('change', ()=> updateFeature(axis, itemId, sel.value, inp.value, funcSel.value));
inp.addEventListener('change', ()=>{ const v = parseInt(inp.value); if (v!==1 && v!==-1) inp.value = v>0 ? '1' : '-1'; updateFeature(axis, itemId, sel.value, inp.value, funcSel.value); });
funcSel.addEventListener('change', ()=> updateFeature(axis, itemId, sel.value, inp.value, funcSel.value));
item.appendChild(sel); item.appendChild(inp); item.appendChild(funcSel); item.appendChild(rm); list.appendChild(item);
const obj = { id: itemId, feature: featureData?.feature || '', weight: parseInt(inp.value)||1, function: featureData?.function || 'linear' };
if (axis==='x') xFeatures.push(obj); else if (axis==='y') yFeatures.push(obj); else zFeatures.push(obj);
}
function updateFeature(axis, id, feature, weight, func) {
const arr = axis==='x'?xFeatures:axis==='y'?yFeatures:zFeatures;
const obj = arr.find(f=>f.id===id);
if (!obj) return; obj.feature = feature; obj.weight = parseInt(weight); obj.function = func; updateChart();
}
// ===== File load & stats =====
function setFileStatus(text, type='success') { const el = document.getElementById('file-status'); el.textContent = text; el.className = `file-status ${type}`; }
function handleFileLoad(e){ const file = e.target.files[0]; if (!file) return; setFileStatus('Loading file...', 'loading'); const reader = new FileReader(); reader.onload = (ev)=>{ try{ const data = JSON.parse(ev.target.result); if (!data.data_points || !data.metadata?.features || !data.attack_stats) throw new Error('Invalid JSON structure'); currentData = data; processedData = data.data_points; document.getElementById('x-features-list').innerHTML=''; document.getElementById('y-features-list').innerHTML=''; document.getElementById('z-features-list').innerHTML=''; xFeatures=[]; yFeatures=[]; zFeatures=[]; addFeatureItem('x'); addFeatureItem('y'); addFeatureItem('z'); setFileStatus(`Loaded: ${data.metadata.total_points.toLocaleString()} points`, 'success'); createLegend(); updateStats(); updateChart(); }catch(err){ console.error(err); setFileStatus('Error: Invalid JSON file', 'error'); } }; reader.readAsText(file); }
function createLegend(){
const legendEl = document.getElementById('legend');
legendEl.innerHTML = '';
if (!currentData?.attack_stats) return;
const sorted = Object.entries(currentData.attack_stats).sort((a,b)=>b[1].count - a[1].count);
for (const [name, stats] of sorted){
const row = document.createElement('div'); row.className='legend-item';
const colorBox = document.createElement('div'); colorBox.className='legend-color'; colorBox.style.backgroundColor = stats.color; row.appendChild(colorBox);
let text = `${name} (${stats.count.toLocaleString()} pts`;
if (stats.original_count && stats.original_count !== stats.count) text += ` / ${stats.original_count.toLocaleString()} orig)`; else text += ')';
const span = document.createElement('span'); span.textContent = text; span.style.color='#333'; span.style.fontWeight = name==='normal' ? 'normal':'bold'; row.appendChild(span);
legendEl.appendChild(row);
}
}
function updateStats(){ const m = currentData.metadata; document.getElementById('total-points').textContent = m.total_points.toLocaleString(); document.getElementById('feature-count').textContent = m.features.length; document.getElementById('attack-classes').textContent = m.attack_classes; if (m.total_original_points){ document.getElementById('original-points').textContent = m.total_original_points.toLocaleString(); document.getElementById('sample-rate').textContent = `${(m.sample_rate*100).toFixed(1)}%`; } else { document.getElementById('original-points').textContent = 'N/A'; document.getElementById('sample-rate').textContent = 'N/A'; } }
// ===== Math helpers (copied/adapted from IF) =====
function applyFunction(x, func) {
switch(func) {
case 'linear': return x;
case 'square': return x * x;
case 'sqrt': return Math.sqrt(Math.max(0, x));
case 'log10': return Math.log10(Math.max(0.0001, x));
case 'natural_log': return Math.log(Math.max(0.0001, x));
case 'inverse': return x !== 0 ? 1 / x : 0;
case 'logit':
const p = Math.max(0.0001, Math.min(0.9999, x));
return (Math.log(p / (1 - p)) + 10) / 20;
case 'sigmoid': return 1 / (1 + Math.exp(-20 * x + 10));
default: return x;
}
}
function calcCombined(d, featuresArr) {
let value = 0; let ok=false;
for (const f of featuresArr) {
if (!f.feature) continue; const v = d[f.feature]; if (v !== null && v !== undefined) { const transformed = applyFunction(v, f.function || 'linear'); value += f.weight * transformed; ok = true; }
}
return ok ? value : null;
}
function bounds(values){ if (!values.length) return [-1,1]; const min = Math.min(...values), max = Math.max(...values); const range = max - min; const fuzz = 0.00001 * range; return [min - fuzz, max + fuzz]; }
function norm(v, lo, hi){ if (hi === lo) return 0.5; return (v - lo) / (hi - lo); }
// ===== Plotly 3D scatter replacement =====
let DEFAULT_CAMERA = null; // stored after first render
function featureSummary(arr){
if (!arr.length) return '(none)';
return arr.map(f=>`${f.weight === -1 ? '-' : '+'}${f.function !== 'linear' ? f.function+':' : ''}${f.feature}`).join(' ');
}
function updateChart(){
if (!processedData) return;
const showNormal = document.getElementById('show-normal').checked;
const pointOpacity = parseFloat(document.getElementById('point-opacity').value);
const pointSizeSel = document.getElementById('point-size').value;
const pointSize = pointSizeSel==='small'?3:pointSizeSel==='large'?9:6;
const xf = xFeatures.filter(f => f.feature && (f.weight===1||f.weight===-1));
const yf = yFeatures.filter(f => f.feature && (f.weight===1||f.weight===-1));
const zf = zFeatures.filter(f => f.feature && (f.weight===1||f.weight===-1));
if (!xf.length || !yf.length || !zf.length){
document.getElementById('chart').innerHTML = '<div class="loading-message"><p>Select at least one feature for each axis.</p></div>';
document.getElementById('visible-points').textContent = '0';
return;
}
const combined = processedData.map(d => {
const x = calcCombined(d, xf);
const y = calcCombined(d, yf);
const z = calcCombined(d, zf);
return { ...d, xCombined:x, yCombined:y, zCombined:z };
}).filter(d => d.xCombined!==null && d.yCombined!==null && d.zCombined!==null && (showNormal || d.attack_name !== 'normal'));
const xb = bounds(combined.map(d=>d.xCombined));
const yb = bounds(combined.map(d=>d.yCombined));
const zb = bounds(combined.map(d=>d.zCombined));
if (axisLock && !lockedB) lockedB = { xb, yb, zb };
const useB = axisLock && lockedB ? lockedB : { xb, yb, zb };
const dataNorm = combined.map(d => ({
...d,
xN: norm(d.xCombined, useB.xb[0], useB.xb[1]),
yN: norm(d.yCombined, useB.yb[0], useB.yb[1]),
zN: norm(d.zCombined, useB.zb[0], useB.zb[1])
}));
document.getElementById('visible-points').textContent = dataNorm.length.toLocaleString();
// Group by attack_name for per-class traces
const groupMap = new Map();
for (const d of dataNorm){
if (!groupMap.has(d.attack_name)) groupMap.set(d.attack_name, { x:[], y:[], z:[], text:[], color:d.attack_color });
const g = groupMap.get(d.attack_name);
// Use normalized values (0..1) for axes
g.x.push(d.xN);
g.y.push(d.yN);
g.z.push(d.zN);
g.text.push(`${d.attack_name}<br>x:${d.xN.toFixed(3)} y:${d.yN.toFixed(3)} z:${d.zN.toFixed(3)}`);
}
const traces = Array.from(groupMap.entries()).map(([name, g]) => ({
type: 'scatter3d',
mode: 'markers',
name,
x: g.x,
y: g.y,
z: g.z,
text: g.text,
hoverinfo: 'text',
marker: { size: pointSize, opacity: pointOpacity, color: g.color, line: { width: 0 } }
}));
const layout = {
autosize: false,
width: width,
height: height,
margin: { l:0, r:0, t:30, b:0 },
showlegend: true,
legend: { font: { size: 11 } },
scene: {
xaxis: { title: 'X (normalized)', range: [0,1] },
yaxis: { title: 'Y (normalized)', range: [0,1] },
zaxis: { title: 'Z (normalized)', range: [0,1] },
aspectmode: 'cube'
},
title: { text: 'Interactive Multi-Feature 3D Scatter (Plotly)', font:{ size:16 } }
};
const config = { responsive: true, displaylogo:false, scrollZoom:true };
const chartDiv = document.getElementById('chart');
if (!chartDiv._plotlyRendered){
Plotly.newPlot(chartDiv, traces, layout, config).then(gd => {
DEFAULT_CAMERA = gd._fullLayout.scene._scene.getCamera();
chartDiv._plotlyRendered = true;
});
} else {
Plotly.react(chartDiv, traces, layout, config);
}
// Update legend panel remains (independent summary)
}
// Reset view integration with Plotly
document.addEventListener('DOMContentLoaded', () => {
const resetBtn = document.getElementById('reset-view');
if (resetBtn){
resetBtn.addEventListener('click', () => {
const chartDiv = document.getElementById('chart');
if (chartDiv && chartDiv._fullLayout){
const camera = DEFAULT_CAMERA || chartDiv._fullLayout.scene.camera; // fallback
Plotly.relayout(chartDiv, { 'scene.camera': camera });
}
});
}
});
// ===== CSV Export adapted for 3D =====
function exportTransformedCSV(){ if(!processedData) return; const showNormal = document.getElementById('show-normal').checked; const xf = xFeatures.filter(f=>f.feature && (f.weight===1||f.weight===-1)); const yf = yFeatures.filter(f=>f.feature && (f.weight===1||f.weight===-1)); const zf = zFeatures.filter(f=>f.feature && (f.weight===1||f.weight===-1)); const combined = processedData.map(d=>{ const x=calcCombined(d,xf); const y=calcCombined(d,yf); const z=calcCombined(d,zf); return {...d, xCombined:x, yCombined:y, zCombined:z}; }).filter(d=>d.xCombined!==null && d.yCombined!==null && d.zCombined!==null && (showNormal||d.attack_name!=='normal')); const xb=bounds(combined.map(d=>d.xCombined)); const yb=bounds(combined.map(d=>d.yCombined)); const zb=bounds(combined.map(d=>d.zCombined)); const data = combined.map(d=>({...d, xN: norm(d.xCombined, xb[0], xb[1]), yN: norm(d.yCombined, yb[0], yb[1]), zN: norm(d.zCombined, zb[0], zb[1]) })); const headers = ['row_index','attack_name','xCombined','yCombined','zCombined','xN','yN','zN']; function cumColName(axis,f){ return `${axis}_cum_${f.feature}`; } xf.forEach(f=>headers.push(cumColName('x',f))); yf.forEach(f=>headers.push(cumColName('y',f))); zf.forEach(f=>headers.push(cumColName('z',f))); function cumNColName(axis,f){ return `${axis}_cumN_${f.feature}`; } xf.forEach(f=>headers.push(cumNColName('x',f))); yf.forEach(f=>headers.push(cumNColName('y',f))); zf.forEach(f=>headers.push(cumNColName('z',f))); const rows = data.map((d,idx)=>{ const row={ row_index: idx, attack_name: d.attack_name, xCombined:d.xCombined, yCombined:d.yCombined, zCombined:d.zCombined, xN:d.xN, yN:d.yN, zN:d.zN }; let xCum=0; xf.forEach(f=>{ const orig = d[f.feature]; if (orig !== null && orig !== undefined){ const transformed = applyFunction(orig, f.function || 'linear'); xCum += f.weight * transformed; } row[cumColName('x',f)] = xCum; row[cumNColName('x',f)] = norm(xCum, xb[0], xb[1]); }); let yCum=0; yf.forEach(f=>{ const orig = d[f.feature]; if (orig !== null && orig !== undefined){ const transformed = applyFunction(orig, f.function || 'linear'); yCum += f.weight * transformed; } row[cumColName('y',f)] = yCum; row[cumNColName('y',f)] = norm(yCum, yb[0], yb[1]); }); let zCum=0; zf.forEach(f=>{ const orig = d[f.feature]; if (orig !== null && orig !== undefined){ const transformed = applyFunction(orig, f.function || 'linear'); zCum += f.weight * transformed; } row[cumColName('z',f)] = zCum; row[cumNColName('z',f)] = norm(zCum, zb[0], zb[1]); }); return headers.map(h=> row[h] ?? ''); }); const csv = [headers.join(',')].concat(rows.map(r=> r.map(v=> formatCSVCell(v)).join(','))).join('\n'); const blob = new Blob([csv], {type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); const ts = new Date().toISOString().replace(/[:.]/g,'-'); a.href = url; a.download = `projection_transformed_3d_${ts}.csv`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }
function formatCSVCell(value){ if (value === null || value === undefined) return ''; if (typeof value === 'number') return Number.isFinite(value)? String(value) : ''; const str = String(value); if (/[",\n]/.test(str)) return '"' + str.replace(/"/g,'""') + '"'; return str; }
</script>
</body>
</html>