-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
366 lines (307 loc) · 10.8 KB
/
Copy pathutil.js
File metadata and controls
366 lines (307 loc) · 10.8 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
window.util = (function () {
var params = (function(){
var rv = {}
rv.get = key => {
var url = new URL(window.location)
var searchParams = new URLSearchParams(url.search)
var str = searchParams.get(key)
return str && decodeURIComponent(str)
}
rv.getAll = () => {
var url = new URL(window.location)
var searchParams = new URLSearchParams(url.search)
var values = {}
for (const [key, value] of searchParams.entries()) {
values[key] = decodeURIComponent(value)
}
return values
}
rv.set = (key, value) => {
var url = new URL(window.location)
var searchParams = new URLSearchParams(url.search)
if (value === null) {
searchParams.delete(key)
} else {
searchParams.set(key, value)
}
url.search = searchParams.toString()
history.replaceState(null, '', url)
}
return rv
})()
async function getFile(path, useCache = true, fileType = null, range = null) {
// Cache storage
var __datacache = window.__datacache = window.__datacache || {}
if (path.startsWith('./features/')) {
path = path.replace('./features/', 'https://d1fk9w8oratjix.cloudfront.net/features/')
}
if (!window.isLocalServing){
if (window.location.hostname === 'localhost' && path.startsWith('./data/')) {
path = path.replace('./data/', 'https://d1fk9w8oratjix.cloudfront.net/data/')
}
if (window.location.hostname === 'localhost' && path.startsWith('./graph_data/')) {
path = path.replace('./graph_data/', 'https://d1fk9w8oratjix.cloudfront.net/graph_data/')
}
}
// Return cached result if available
var cacheKey = path + (range ? `-${range}` : '') + (fileType ? `-${fileType}` : '')
if (!useCache || !__datacache[cacheKey]) __datacache[cacheKey] = __fetch()
return __datacache[cacheKey]
async function __fetch() {
var cacheOption = useCache ? 'force-cache' : 'no-cache'
var headers = range ? {'Range': range} : {}
var res = await fetch(path, {cache: cacheOption, headers})
if (!res.ok) {
var resText = await res.text().catch(() => '')
console.log(resText, res)
throw new Error('HTTP ' + res.status + ' for ' + path)
}
// Strip ?query / #hash so "./foo.npy?t=1" still detects as npy
var type = fileType || path.replaceAll('..', '').split('?')[0].split('#')[0].split('.').at(-1)
if (type == 'csv') {
return d3.csvParse(await res.text())
} else if (type == 'npy') {
return npyjs.parse(await res.arrayBuffer())
} else if (type == 'json') {
return await res.json()
} else if (type == 'jsonl') {
var text = await res.text()
return text.split(/\r?\n/).filter(d => d).map(line => JSON.parse(line))
} else if (type == 'json.gz' || type == 'gz' && path.endsWith('.json.gz')) {
var compressedData = await res.arrayBuffer()
var decompressed = pako.inflate(new Uint8Array(compressedData), { to: 'string' })
return JSON.parse(decompressed)
} else if (type == 'bin') {
var bytes = new Uint8Array(await res.arrayBuffer())
var dataLength = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)
var decompressed = pako.inflate(bytes.slice(4, 4 + dataLength), { to: 'string' })
return JSON.parse(decompressed)
} else {
return await res.text()
}
}
}
/** Seed the getFile cache so an uploaded graph can be loaded by slug. */
function putFileCache(path, data) {
var __datacache = window.__datacache = window.__datacache || {}
__datacache[path] = Promise.resolve(data)
}
/** Relative graph-data URL so project Pages (`/repo/graph_data/…`) work. */
function graphDataUrl(rel) {
var base = (window.GRAPH_DATA_BASE || './graph_data/').replace(/\/?$/, '/')
return base + String(rel || '').replace(/^\/+/, '')
}
function addAxisLabel(c, xText, yText, title='', xOffset=0, yOffset=0, titleOffset=0){
c.svg.select('.x').append('g')
.translate([c.width/2, xOffset + 25])
.append('text.axis-label')
.text(xText)
.at({textAnchor: 'middle', fill: '#000'})
c.svg.select('.y')
.append('g')
.translate([yOffset -30, c.height/2])
.append('text.axis-label')
.text(yText)
.at({textAnchor: 'middle', fill: '#000', transform: 'rotate(-90)'})
c.svg
.append('g.axis').at({fontFamily: 'sans-serif'})
.translate([c.width/2, titleOffset -10])
.append('text.axis-label.axis-title')
.text(title)
.at({textAnchor: 'middle', fill: '#000'})
}
function ggPlot(c){
c.svg.append('rect.bg-rect')
.at({width: c.width, height: c.height, fill: c.isBlack ? '#000' : '#EAECED'}).lower()
c.svg.selectAll('.domain').remove()
c.svg.selectAll('.x text').at({y: 4})
c.svg.selectAll('.x .tick')
.selectAppend('path').at({d: 'M 0 0 V -' + c.height, stroke: c.isBlack ? '#444' : '#fff', strokeWidth: 1})
c.svg.selectAll('.y text').at({x: -3})
c.svg.selectAll('.y .tick')
.selectAppend('path').at({d: 'M 0 0 H ' + c.width, stroke: c.isBlack? '#444' : '#fff', strokeWidth: 1})
ggPlotUpdate(c)
}
function ggPlotUpdate(c){
c.svg.selectAll('.tick').selectAll('line').remove()
c.svg.selectAll('.x text').at({y: 4})
c.svg.selectAll('.x .tick')
.selectAppend('path').at({d: 'M 0 0 V -' + c.height, stroke: c.isBlack ? '#444' : '#fff', strokeWidth: 1})
c.svg.selectAll('.y text').at({x: -3})
c.svg.selectAll('.y .tick')
.selectAppend('path').at({d: 'M 0 0 H ' + c.width, stroke: c.isBlack? '#444' : '#fff', strokeWidth: 1})
}
function initRenderAll(fnLabels){
var rv = {}
fnLabels.forEach(label => {
rv[label] = (ev) => Object.values(rv[label].fns).forEach(d => d(ev))
rv[label].fns = []
})
return rv
}
function attachRenderAllHistory(renderAll, skipKeys=['hoverId', 'hoverIdx']) {
// Add state pushing to each render function
Object.keys(renderAll).forEach(key => {
renderAll[key].fns.push(() => {
if (skipKeys.includes(key)) return
var simpleVisState = {...visState}
skipKeys.forEach(key => delete simpleVisState[key])
var url = new URL(window.location)
if (visState[key] == url.searchParams.get(key)) return
url.searchParams.set(key, simpleVisState[key])
history.pushState(simpleVisState, '', url)
})
})
// Handle back/forward navigation
d3.select(window).on('popstate.updateState', ev => {
if (!ev.state) return
ev.preventDefault()
Object.keys(renderAll).forEach(key => {
if (skipKeys.includes(key)) return
if (visState[key] == ev.state[key]) return
visState[key] = ev.state[key]
renderAll[key]()
})
})
}
function throttle(fn, delay){
var lastCall = 0
return (...args) => {
if (Date.now() - lastCall < delay) return
lastCall = Date.now()
fn(...args)
}
}
function debounce(fn, delay) {
var timeout
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => fn(...args), delay)
}
}
function throttleDebounce(fn, delay) {
var lastCall = 0
var timeoutId
return function (...args) {
clearTimeout(timeoutId)
var remainingDelay = delay - (Date.now() - lastCall)
if (remainingDelay <= 0) {
lastCall = Date.now()
fn.apply(this, args)
} else {
timeoutId = setTimeout(() => {
lastCall = Date.now()
fn.apply(this, args)
}, remainingDelay)
}
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
function cantorUnpair(z) {
const w = Math.floor((Math.sqrt(8 * z + 1) - 1) / 2)
const t = (w * w + w) / 2
const y = z - t
const x = w - y
return [x, y]
}
function cache(fn){
var cache = {}
return function(...args){
var key = JSON.stringify(args)
if (!(key in cache)) cache[key] = fn.apply(this, args)
return cache[key]
}
}
async function initGraphSelect(sel, cgSlug){
var {graphs} = await util.getFile('./data/graph-metadata.json')
var selectSel = sel.html('').append('select.graph-prompt-select')
.on('change', function() {
cgSlug = this.value
// visState.clickedId = undefined
util.params.set('slug', this.value)
render()
})
var cgSel = sel.append('div.cg-container')
selectSel.appendMany('option', graphs)
.text(d => {
var scanName = util.nameToPrettyPrint[d.scan] || d.scan
var prefix = d.title_prefix ? d.title_prefix + ' ' : ''
return prefix + scanName + ' — ' + d.prompt
})
.attr('value', d => d.slug)
.property('selected', d => d.slug === cgSlug)
function render() {
initCg(cgSel.html(''), cgSlug, {
isModal: true,
// clickedId: visState.clickedId,
// clickedIdCb: id => util.params.set('clickedId', id)
})
var m = graphs.find(g => g.slug == cgSlug)
if (!m) return
selectSel.at({title: m.prompt})
}
render()
}
function attachCgLinkEvents(sel, cgSlug, figmaSlug){
sel
.on('mouseover', () => util.getFile(`./graph_data/${cgSlug}.json`))
.on('click', (ev) => {
ev.preventDefault()
if (window.innerWidth < 900 || window.innerHeight < 500) {
return window.open(`./static_js/attribution_graphs/index.html?slug=${cgSlug}`, '_blank')
}
d3.select('body').classed('modal-open', true)
var contentSel = d3.select('modal').classed('is-active', 1)
.select('.modal-content').html('')
util.initGraphSelect(contentSel, cgSlug)
util.params.set('slug', cgSlug)
if (figmaSlug) history.replaceState(null, '', '#' + figmaSlug)
})
}
// TODO: tidy
function ppToken(d){
return d
}
function ppClerp(d){
return d
}
var scanSlugToName = {
'h35': 'jackl-circuits-runs-1-4-sofa-v3_0',
'18l': 'jackl-circuits-runs-1-1-druid-cp_0',
'moc': 'jackl-circuits-runs-12-19-valet-m_0'
}
var nameToPrettyPrint = {
'jackl-circuits-runs-1-4-sofa-v3_0': 'Haiku',
'jackl-circuits-runs-1-1-druid-cp_0': '18L',
'jackl-circuits-runs-12-19-valet-m_0': 'Model Organism',
'jackl-circuits-runs-1-12-rune-cp3_0': '18L PLTs',
'gemma-2-2b': 'Gemma-2-2B',
'gemmascope-transcoder-16k': 'GemmaScope PLT',
}
return {
scanSlugToName,
nameToPrettyPrint,
params,
getFile,
putFileCache,
graphDataUrl,
addAxisLabel,
ggPlot,
ggPlotUpdate,
initRenderAll,
attachRenderAllHistory,
throttle,
debounce,
throttleDebounce,
sleep,
cache,
initGraphSelect,
attachCgLinkEvents,
ppToken,
ppClerp,
cantorUnpair,
}
})()
window.init?.()