@graphty/cytoscape-extensions 0.0.28 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/algorithm-options.d.ts +5 -0
  2. package/dist/algorithm-options.d.ts.map +1 -0
  3. package/dist/algorithm-options.js +285 -0
  4. package/dist/algorithm-options.js.map +1 -0
  5. package/dist/algorithms.d.ts +489 -0
  6. package/dist/algorithms.d.ts.map +1 -0
  7. package/dist/algorithms.js +1184 -0
  8. package/dist/algorithms.js.map +1 -0
  9. package/dist/cdn/chunks/elements-DIunzJUl.js +1 -0
  10. package/dist/cdn/chunks/gpu-platform-browser-DnQwf3s0.js +2825 -0
  11. package/dist/cdn/chunks/index-C-jUF_Ve.js +1 -0
  12. package/dist/cdn/chunks/index-C4RZkds_.js +10 -0
  13. package/dist/cdn/chunks/io-D-Vr0j3W.js +269 -0
  14. package/dist/cdn/chunks/preload-helper-Crt_PPe8.js +1 -0
  15. package/dist/cdn/chunks/samples-Dja23zzq.js +1 -0
  16. package/dist/cdn/chunks/sigv4-BXwVbza3-DZCCNyQA.js +3 -0
  17. package/dist/cdn/chunks/sources-cypher-oj3S6pKb.js +5 -0
  18. package/dist/cdn/chunks/sources-ndex-BgZhxHsL.js +1 -0
  19. package/dist/cdn/chunks/sources-rest-E6On5P3z.js +1 -0
  20. package/dist/cdn/chunks/sources-sparql-BAxh1dw-.js +5 -0
  21. package/dist/cdn/cytoscape-extensions.js +1 -0
  22. package/dist/cdn/io.js +1 -0
  23. package/dist/cytoscape-extensions.bundle.js +2825 -0
  24. package/dist/elements.d.ts +69 -0
  25. package/dist/elements.d.ts.map +1 -0
  26. package/dist/elements.js +343 -0
  27. package/dist/elements.js.map +1 -0
  28. package/dist/gpu-platform-browser.d.ts +11 -0
  29. package/dist/gpu-platform-browser.d.ts.map +1 -0
  30. package/dist/gpu-platform-browser.js +22 -0
  31. package/dist/gpu-platform-browser.js.map +1 -0
  32. package/dist/gpu-platform-node.d.ts +15 -0
  33. package/dist/gpu-platform-node.d.ts.map +1 -0
  34. package/dist/gpu-platform-node.js +27 -0
  35. package/dist/gpu-platform-node.js.map +1 -0
  36. package/dist/gpu.d.ts +149 -0
  37. package/dist/gpu.d.ts.map +1 -0
  38. package/dist/gpu.js +312 -0
  39. package/dist/gpu.js.map +1 -0
  40. package/dist/graph-data.d.ts +101 -0
  41. package/dist/graph-data.d.ts.map +1 -0
  42. package/dist/graph-data.js +147 -0
  43. package/dist/graph-data.js.map +1 -0
  44. package/dist/index.d.ts +36 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +48 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/io.d.ts +111 -0
  49. package/dist/io.d.ts.map +1 -0
  50. package/dist/io.js +258 -0
  51. package/dist/io.js.map +1 -0
  52. package/dist/layouts.d.ts +207 -0
  53. package/dist/layouts.d.ts.map +1 -0
  54. package/dist/layouts.js +615 -0
  55. package/dist/layouts.js.map +1 -0
  56. package/dist/lazy.d.ts +21 -0
  57. package/dist/lazy.d.ts.map +1 -0
  58. package/dist/lazy.js +32 -0
  59. package/dist/lazy.js.map +1 -0
  60. package/dist/samples.d.ts +115 -0
  61. package/dist/samples.d.ts.map +1 -0
  62. package/dist/samples.js +237 -0
  63. package/dist/samples.js.map +1 -0
  64. package/dist/snapshot.d.ts +81 -0
  65. package/dist/snapshot.d.ts.map +1 -0
  66. package/dist/snapshot.js +225 -0
  67. package/dist/snapshot.js.map +1 -0
  68. package/dist/webgpu-provider.d.ts +25 -0
  69. package/dist/webgpu-provider.d.ts.map +1 -0
  70. package/dist/webgpu-provider.js +53 -0
  71. package/dist/webgpu-provider.js.map +1 -0
  72. package/package.json +13 -9
@@ -0,0 +1,2825 @@
1
+ var graphtyCytoscape=(function(){"use strict";var bu=typeof document<"u"&&document.currentScript&&document.currentScript.src;function vu(n){return bu?import(new URL("cdn/"+n,bu).href):Promise.reject(new Error("graphty: the script-tag bundle loads the file formats from dist/cdn/ next to itself, but it was not loaded by a <script src> tag, so it cannot tell where that is. Load it with <script src>, or use the ES module build: <script type='module'> importing https://cdn.jsdelivr.net/npm/@graphty/cytoscape-extensions/dist/cdn/cytoscape-extensions.js"))}const x=4294967295,Te=4294967294,Mr=1,Au=Symbol.for("@graphty/graph-format/snapshot"),ft=256,Eu=new Uint8Array(new Uint16Array([1]).buffer)[0]===1,zn=1,_u=0,la="graphty-snapshot",ua=[71,83,78,80],da=16909060,C0=Object.freeze({});class P extends Error{constructor(e,t,r){super(t),this.name="GraphFormatError",this.code=e,this.details=r===void 0?C0:Object.freeze({...r})}}const Ur=new WeakMap;function it(n){Ur.set(n,(Ur.get(n)??0)+1)}function Gn(n){Ur.set(n,Math.max(Ur.get(n)??0,1)+1)}function N0(n){return Ur.get(n)??0}function Fr(n){return(Ur.get(n)??0)>1}const T0=32;let Iu=null,ku=null;function Su(){return Iu??=new TextDecoder("utf-8",{ignoreBOM:!0}),Iu}function O0(){return ku??=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),ku}function $0(n){let e=0;const t=n.length;for(let r=0;r<t;r++){const o=n.charCodeAt(r);if(o<128)e+=1;else if(o<2048)e+=2;else if(o>=55296&&o<=56319&&r+1<t){const s=n.charCodeAt(r+1);s>=56320&&s<=57343?(e+=4,r++):e+=3}else e+=3}return e}function R0(n,e,t){let r=t;const o=n.length;for(let s=0;s<o;s++){let i=n.charCodeAt(s);if(i<128){e[r++]=i;continue}if(i<2048){e[r++]=192|i>>6,e[r++]=128|i&63;continue}if(i>=55296&&i<=57343){const a=D0(n,s,i);if(a>=0){s++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63;continue}i=65533}e[r++]=224|i>>12,e[r++]=128|i>>6&63,e[r++]=128|i&63}return r}function D0(n,e,t){if(t>56319||e+1>=n.length)return-1;const r=n.charCodeAt(e+1);return r<56320||r>57343?-1:65536+(t-55296<<10)+(r-56320)}const L0=13;function Ro(n){return n.length<L0?n:` ${n}`.slice(1)}function Pu(n){const e=n.length;for(let t=0;t<e;t++){const r=n.charCodeAt(t);if(r<55296||r>57343)continue;if(r>56319||t+1>=e)return!0;const o=n.charCodeAt(t+1);if(o<56320||o>57343)return!0;t++}return!1}function xu(n,e,t){const r=t-e;if(r===0)return"";if(r<=T0){let o="",s=e;for(;s<t;s++){const i=n[s];if(i>=128)break;o+=String.fromCharCode(i)}if(s===t)return o}return Su().decode(n.subarray(e,t))}function M0(n,e,t){for(let r=e;r<t;r++)if(n[r]>=128)return!1;return!0}function fa(n,e,t,r){const o=new Array(r-t);if(r<=t)return o;const s=e[t],i=e[r];if(M0(n,s,i)){const a=Su().decode(n.subarray(s,i));for(let c=t;c<r;c++)o[c-t]=a.substring(e[c]-s,e[c+1]-s);return o}for(let a=t;a<r;a++)o[a-t]=xu(n,e[a],e[a+1]);return o}function U0(n,e,t){let r=!0;for(let o=e;o<t;o++)if(n[o]>=128){r=!1;break}if(r)return!0;try{return O0().decode(n.subarray(e,t)),!0}catch{return!1}}function Do(n,e){const t=new Uint32Array(e+1);let r=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(r+=$0(a)),t[i+1]=r}const o=new Uint8Array(r);let s=0;for(let i=0;i<e;i++){const a=n[i];typeof a=="string"&&(s=R0(a,o,s))}return{offsets:t,utf8:o}}function ha(n,e,t,r){if(n.length!==t+1)throw new P("E_BAD_SERIALIZATION",`${r}: expected ${t+1} offsets, found ${n.length}`,{ref:r,reason:"offsets length",expected:t+1,found:n.length});let o=n[0];for(let s=1;s<=t;s++){const i=n[s];if(i<o)throw new P("E_BAD_SERIALIZATION",`${r}: offsets decrease at row ${s-1}`,{ref:r,reason:"offsets not monotonic",row:s-1});o=i}if(o>e.length)throw new P("E_BAD_SERIALIZATION",`${r}: offsets end at ${o} but the byte store has ${e.length} bytes`,{ref:r,reason:"offsets exceed utf8",end:o,byteLength:e.length})}class Wn{constructor(e,t,r){this.length=e,this.source=t,this.cache=null,this.encodedArrays=r}static fromStrings(e,t=e.length){return new Wn(t,e,null)}static fromEncoded(e,t){return new Wn(Math.max(0,e.length-1),null,{offsets:e,utf8:t})}get encoded(){return this.encodedArrays!==null}get decoded(){return this.source!==null}get detached(){return this.source===null&&this.length>0&&this.encodedArrays!==null&&this.encodedArrays.offsets.length===0}get offsets(){return this.ensureEncoded().offsets}get utf8(){return this.ensureEncoded().utf8}at(e){if(!(e>=0&&e<this.length)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`row ${e} out of range (length ${this.length})`,{index:e,size:this.length});if(this.source!==null)return this.source[e];this.cache??=new Array(this.length);const t=this.cache[e];if(t!==void 0)return t;const{offsets:r,utf8:o}=this.ensureEncoded(),s=xu(o,r[e],r[e+1]);return this.cache[e]=s,s}slice(e=0,t=this.length){const[r,o]=Cu(e,t,this.length),{source:s}=this;if(s!==null){const c=new Array(o-r);for(let l=r;l<o;l++)c[l-r]=s[l];return c}const{offsets:i,utf8:a}=this.ensureEncoded();return fa(a,i,r,o)}decodeAll(){return this.slice(0,this.length)}materialiseDecoded(){this.source===null&&(this.source=this.decodeAll(),this.cache=null)}byteLength(){const e=this.encodedArrays;return e===null?0:e.offsets.byteLength+e.utf8.byteLength}firstMalformedRow(){const e=this.encodedArrays;if(this.source!==null||e===null)return-1;const{offsets:t,utf8:r}=e;for(let o=0;o<this.length;o++)if(!U0(r,t[o],t[o+1]))return o;return-1}ensureEncoded(){let e=this.encodedArrays;return e===null&&(e=Do(this.source,this.length),this.encodedArrays=e,it(e.offsets.buffer),it(e.utf8.buffer)),e}}function Cu(n,e,t){let r=Math.trunc(n),o=Math.trunc(e);return Number.isNaN(r)&&(r=0),Number.isNaN(o)&&(o=0),r=r<0?Math.max(t+r,0):Math.min(r,t),o=o<0?Math.max(t+o,0):Math.min(o,t),[r,Math.max(r,o)]}function F0(){try{const n=new ArrayBuffer(0,{maxByteLength:64});return!n.resizable||typeof n.resize!="function"?!1:(n.resize(64),n.byteLength===64&&n.maxByteLength===64)}catch{return!1}}const ga=F0(),wa=16,B0=64,Nu=1024*1024,z0=16,G0=256*1024*1024;function Lo(n,e){const t=n%e;return t===0?n:n+e-t}function Mo(n){return Lo(n,4)}function W0(n){return Math.ceil(n/4)}function hr(n,e=ft){return Lo(n,e)}function V0(n,e=ft){const t=[],r=[];let o=0,s=0;for(const i of n){if(i===0){t.push(null),r.push(null);continue}const a=hr(o,e);s+=a-o,t.push(a),o=a+i,r.push(o)}return{offsets:t,ends:r,byteLength:o,padding:s}}function j0(n){return n.byteOffset%4===0&&n.byteLength%4===0}function pa(n){const{buffer:e}=n;return e instanceof ArrayBuffer&&!e.resizable}function Ds(n){return n.byteOffset%4===0&&n.byteOffset+Mo(n.byteLength)<=n.buffer.byteLength}function q0(n){if(!Ds(n))throw new P("E_COLUMN_ALIGNMENT",`u8 array at byteOffset ${n.byteOffset} with byteLength ${n.byteLength} has no zero-copy padded u32 view`,{byteOffset:n.byteOffset,byteLength:n.byteLength,bufferByteLength:n.buffer.byteLength});return new Uint32Array(n.buffer,n.byteOffset,W0(n.byteLength))}function H0(n){const e=new Uint8Array(new ArrayBuffer(Mo(n.byteLength)),0,n.byteLength);return e.set(n),e}function K0(n){throw new P("E_UNSUPPORTED",`unsupported dtype ${String(n)}`,{dtype:n})}function Y0(n,e){return Lo(Math.max(e,n*2,wa),wa)}function Tu(n,e){return Lo(n*e,B0)}function Ou(n,e=ga,t=Nu){if(!e)return new ArrayBuffer(n);const r=Math.max(n,t);try{return new ArrayBuffer(n,{maxByteLength:r})}catch(o){if(o instanceof RangeError&&r>n)return new ArrayBuffer(n,{maxByteLength:n});throw o}}function $u(n,e,t,r=ga){if(t<=n.length)return n;const o=e.BYTES_PER_ELEMENT,s=Tu(Y0(n.length,t),o),i=s/o,{buffer:a}=n;if(a.resizable&&n.byteOffset===0&&s<=a.maxByteLength)return a.resize(s),new e(a,0,i);const c=Math.max(a.maxByteLength*2,Math.min(a.maxByteLength*z0,G0),Nu),l=new e(Ou(s,r,c),0,i);return l.set(n),l}const ma=4294967295;function Fe(n){return Math.ceil(n/32)}function Ru(n){const e=n%32;return e===0?ma:ma>>>32-e}function ya(n,e){const t=Fe(e);t>0&&t<=n.length&&e%32!==0&&(n[t-1]&=Ru(e)),t<n.length&&n.fill(0,t)}function In(n,e=!1){const t=new Uint32Array(Fe(n));return e&&(t.fill(ma),ya(t,n)),t}function Le(n,e){return(n[e>>>5]>>>(e&31)&1)===1}function Ht(n,e){n[e>>>5]|=1<<(e&31)}function Kt(n,e){n[e>>>5]&=~(1<<(e&31))}function ba(n,e,t){t?Ht(n,e):Kt(n,e)}function Du(n){let e=n-(n>>>1&1431655765);return e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,Math.imul(e,16843009)>>>24}function gr(n,e){const t=Math.floor(e/32);let r=0;for(let o=0;o<t;o++)r+=Du(n[o]);return e%32!==0&&(r+=Du(n[t]&Ru(e))),r}function X0(n,e){const t=new Uint32Array(gr(n,e));let r=0;for(let o=0;o<e;o++)(n[o>>>5]>>>(o&31)&1)===1&&(t[r++]=o);return t}function Lu(n,e,t){const r=Math.max(0,t-e),o=In(r);if(r===0)return o;const s=e>>>5,i=e&31;if(i===0)o.set(n.subarray(s,s+o.length));else{const a=32-i;for(let c=0;c<o.length;c++){const l=s+c,u=l<n.length?n[l]>>>i:0,d=l+1<n.length?n[l+1]<<a:0;o[c]=u|d}}return ya(o,r),o}function wr(n,e){if(Pu(n))throw new P("E_COLUMN_TYPE","string value contains a lone surrogate",{...e,reason:"lone surrogate"})}function Q0(n){const e=new Map;for(let t=0;t<n.length;t++){const r=n[t];e.has(r)||e.set(r,t)}return e}class J0{constructor(e){if(this.values=[],this.codes=new Map,e!==void 0)for(const t of e)this.intern(t)}get size(){return this.values.length}intern(e){const t=this.codes.get(e);if(t!==void 0)return t;wr(e);const r=this.values.length,o=Ro(e);return this.values.push(o),this.codes.set(o,r),r}codeOf(e){const t=this.codes.get(e);return t===void 0?x:t}has(e){return this.codes.has(e)}}const Z0=["bool","i32","f64","string","json"],ey=/^-?(0|[1-9]\d*)$/,ty=/^[+-]?((0|[1-9]\d*)(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/,Mu=-2147483648,Uu=2147483647;function pr(n){return Z0.indexOf(n)}function Fu(n,e){return n===null?e:e===null?n:pr(e)>pr(n)?e:n}function ny(n){if(n==="true"||n==="false")return"bool";if(ey.test(n)){const e=Number(n);return e>=Mu&&e<=Uu?"i32":Number.isFinite(e)?"f64":"string"}return ty.test(n)&&Number.isFinite(Number(n))?"f64":"string"}function Ls(n){if(n==null)return null;switch(typeof n){case"boolean":return"bool";case"number":return Number.isInteger(n)&&n>=Mu&&n<=Uu?"i32":"f64";case"string":return"string";case"object":return"json";default:throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a column`,{reason:"unsupported value type",found:typeof n})}}function Br(n,e){switch(e){case"bool":if(typeof n=="boolean")return n;break;case"i32":case"f64":if(typeof n=="number")return n;if(typeof n=="boolean")return n?1:0;break;case"string":if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);break;case"json":return n;default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}throw new P("E_COLUMN_TYPE",`a ${typeof n} value cannot be stored in a ${e} column`,{dtype:e,found:typeof n})}function Bu(n){let e=null;for(const t of n)if(e=Fu(e,Ls(t)),e==="json")break;return e}class zu{constructor(){this.current=null}get dtype(){return this.current}observeValue(e){return this.apply(Ls(e))}observeText(e){return this.apply(ny(e))}widenTo(e){return this.apply(e)}apply(e){const t=Fu(this.current,e);return t===this.current?!1:(this.current=t,!0)}}const Gu=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),ry=new Set(["f32","f64","i32","u32","u8"]),Wu=16,Vu=256,oy=-2147483648,sy=2147483647,iy=4294967295,ay=255,cy=new TextDecoder,Ms=new WeakMap;function mr(n){return new Uint8Array(new ArrayBuffer(Mo(n)),0,n)}function ly(n){switch(n){case"f32":case"i32":case"u32":case"dict":return"direct";case"u8":case"bool":return"packed";case"f64":return"convert";case"string":case"list":case"json":return"none";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function uy(n){return n!=="list"&&Gu.has(n)}function kn(n){if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function cn(n,e,t=0){if(!(n===null||typeof n=="boolean"||typeof n=="number")){if(typeof n=="string"){wr(n,{field:e});return}if(t>Vu)throw new P("E_COLUMN_TYPE",`${e} is nested deeper than ${Vu} levels`,{field:e,reason:"nesting"});if(Array.isArray(n)){for(const r of n)cn(r,e,t+1);return}if(kn(n)){for(const r of Object.keys(n))cn(n[r],e,t+1);return}throw new P("E_COLUMN_TYPE",`${e} is not a JSON value`,{field:e,found:n===void 0?"undefined":typeof n})}}function Vn(n){if(Array.isArray(n))return n.map(e=>Vn(e));if(kn(n)){const e={};for(const t of Object.keys(n))t==="__proto__"?Object.defineProperty(e,t,{value:Vn(n[t]),enumerable:!0,writable:!0,configurable:!0}):e[t]=Vn(n[t]);return e}return n}function yr(n,e){switch(n){case"f32":case"f64":return!0;case"i32":return Number.isInteger(e)&&e>=oy&&e<=sy;case"u32":return Number.isInteger(e)&&e>=0&&e<=iy;case"u8":return Number.isInteger(e)&&e>=0&&e<=ay;default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function ju(n,e,t){if(typeof t=="number")return yr(n,t)?t:null;if(e>1&&Array.isArray(t)&&t.length===e){const r=t[0];if(typeof r!="number"||!yr(n,r))return null;for(let o=1;o<e;o++)if(!Object.is(t[o],r))return null;return r}return null}function Qe(n,e,t){return new P("E_COLUMN_TYPE",e,{...t,field:n})}function dy(n){if(n===void 0)return null;if(!kn(n))throw Qe("origin","origin must be a plain object");const e=t=>{const r=n[t];if(r==null)return null;if(typeof r!="string")throw Qe("origin",`origin.${t} must be a string or null`,{found:typeof r});return r};return{format:e("format"),id:e("id"),title:e("title"),type:e("type"),namespace:e("namespace")}}function qu(n,e,t){if(e===void 0)return 1;if(!Number.isInteger(e)||e<1||e>Wu)throw Qe(n,`${n} must be an integer in 1..${Wu}, found ${e}`,{found:e});if(e>1&&!ry.has(t))throw Qe(n,`${n} > 1 is only allowed for f32 / f64 / i32 / u32 / u8, not ${t}`,{found:e,dtype:t});return e}function fy(n,e,t,r,o,s){switch(n){case"f32":case"f64":case"i32":case"u32":case"u8":{if(t!==void 0){if(typeof t!="number")throw Qe("fill",`fill of a ${n} column must be a number`,{found:typeof t});return t}return s!==null?x:ju(n,e,r)??0}case"bool":{if(t!==void 0){if(typeof t!="boolean")throw Qe("fill","fill of a bool column must be a boolean",{found:typeof t});return t}return typeof r=="boolean"?r:!1}case"dict":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a dict column must be a string",{found:typeof t});return t}return typeof r=="string"&&(o===null||o.includes(r))?r:o!==null&&o.length>0&&typeof o[0]=="string"?o[0]:""}case"string":{if(t!==void 0){if(typeof t!="string")throw Qe("fill","fill of a string column must be a string",{found:typeof t});return t}return""}case"list":case"json":{if(t!==void 0&&t!=="")throw Qe("fill",`a ${n} column takes no fill value`,{found:t});return""}default:{const i=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}function ht(n,e,t){const{dtype:r}=t;if(r===void 0||!Gu.has(r))throw Qe("dtype",`column "${n}" has no valid dtype`,{name:n,found:r});const o=qu("components",t.components,r);let s=null,i=null;if(r==="list"){const{itemDtype:h}=t;if(h===void 0||!uy(h))throw Qe("itemDtype",`list column "${n}" needs a scalar itemDtype`,{name:n,found:h});s=h,i=qu("itemComponents",t.itemComponents,h)}else if(t.itemDtype!==void 0||t.itemComponents!==void 0)throw Qe("itemDtype",`itemDtype / itemComponents are only allowed on list columns, not ${r}`,{name:n,dtype:r});const a=t.refersTo??null;if(a!==null){if(a!=="node"&&a!=="edge")throw Qe("refersTo",'refersTo must be "node" or "edge"',{found:a});if(!(r==="u32"&&o===1||r==="list"&&s==="u32"&&i===1))throw Qe("refersTo",`refersTo requires a u32 column or a list of u32, not ${r}`,{name:n,dtype:r})}const c=t.default;c!==void 0&&cn(c,"default");let l=null;if(t.options!==void 0){if(!Array.isArray(t.options))throw Qe("options","options must be an array");if(cn(t.options,"options"),r==="dict"){for(const h of t.options)if(typeof h!="string")throw Qe("options","options of a dict column must be strings",{found:typeof h})}l=Object.freeze(Vn([...t.options]))}const u=t.extra??{};if(!kn(u))throw Qe("extra","extra must be a plain object");cn(u,"extra");const d=t.role??null;if(d!==null&&typeof d!="string")throw Qe("role","role must be a string",{found:typeof d});const f=fy(r,o,t.fill,c,l,a);return Object.freeze({name:n,domain:e,dtype:r,components:o,itemDtype:s,itemComponents:i,nullable:t.nullable??!0,mutable:t.mutable??!1,role:d,refersTo:a,unique:t.unique??!1,default:Vn(c),fill:f,options:l,origin:dy(t.origin),dynamic:t.dynamic??!1,extra:Object.freeze(Vn({...u}))})}function Sn(n){return{name:n.name,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype??void 0,itemComponents:n.itemComponents??void 0,nullable:n.nullable,mutable:n.mutable,role:n.role??void 0,refersTo:n.refersTo??void 0,unique:n.unique,default:n.default,fill:n.fill,options:n.options??void 0,origin:n.origin??void 0,dynamic:n.dynamic,extra:n.extra}}class br{constructor(e,t,r,o,s){this.versionValue=0,this.defaultCache=null,this.dtype=e,this.meta=t,this.length=r,this.gpu=ly(e),this.validityWords=o,this.nullCountValue=s,this.defaultValue=Vn(t.default)}get validity(){return this.validityWords}get nullCount(){return this.nullCountValue}get version(){return this.versionValue}get paddedByteLength(){return this.byteLength}get validityByteLength(){return this.validityWords===null?0:this.validityWords.byteLength}get detached(){if(this.length===0)return!1;const e=this.validityWords;return e!==null&&e.length===0||this.storageDetached()}isSet(e){if(!(e>=0&&e<this.length))return!1;const t=this.validityWords;if(t===null)return!0;if(t.length===0)throw this.detachedError();return Le(t,e)}value(e){if(this.assertAttached(),!(Number.isInteger(e)&&e>=0&&e<this.length))throw new P("E_INDEX_RANGE",`row ${e} is out of range for a column of ${this.length} rows`,{row:e,length:this.length,column:this.meta.name});const t=this.validityWords;if(t!==null&&!Le(t,e)){const{defaultValue:r}=this;return r===void 0?void 0:Vn(r)}return this.readValue(e)}materializeDefault(){if(this.assertAttached(),this.meta.default===void 0)throw new P("E_NO_DEFAULT",`column "${this.meta.name}" declares no default`,{column:this.meta.name});return this.nullCountValue===0||this.fillIsDefault()?this.self():(this.defaultCache??=this.withDefaults(),this.defaultCache)}paddedU32View(){throw new P("E_GPU_INELIGIBLE",`a ${this.dtype} column has no u32 view`,{column:this.meta.name,dtype:this.dtype})}markDirty(){this.assertMutable("markDirty"),this.assertAttached(),this.versionValue++,this.defaultCache=null,Ms.delete(this);const e=this.validityWords;e!==null&&(this.nullCountValue=this.length-gr(e,this.length))}mutableValidity(){return this.assertMutable("mutableValidity"),this.validityWords}setAll(){this.assertMutable("setAll"),this.validityWords=null,this.nullCountValue=0,this.versionValue++,this.defaultCache=null}assertAttached(){if(this.detached)throw this.detachedError()}detachedError(){return new P("E_DETACHED",`column "${this.meta.name}" was transferred away`,{column:this.meta.name})}assertMutable(e){if(!this.meta.mutable)throw new P("E_COLUMN_IMMUTABLE",`${e}() on immutable column "${this.meta.name}"`,{column:this.meta.name,operation:e})}checkRange(e,t){if(this.assertAttached(),!(Number.isInteger(e)&&Number.isInteger(t)&&e>=0&&e<=t&&t<=this.length))throw new P("E_INDEX_RANGE",`row range [${e}, ${t}) is invalid for ${this.length} rows`,{start:e,end:t,length:this.length,column:this.meta.name})}sliceValidity(e,t){const r=this.validityWords;if(r===null)return{validity:null,nullCount:0};const o=t-e,s=e%32===0?zr(r.subarray(e>>>5,(e>>>5)+Fe(o))):Lu(r,e,t);return{validity:s,nullCount:o-gr(s,o)}}cloneValidity(){return this.assertAttached(),this.validityWords===null?null:this.validityWords.slice()}}function zr(n){return Gn(n.buffer),n}class Uo extends br{constructor(e,t,r,o,s,i){super(e,t,r,s,i),this.data=o}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}storageDetached(){return this.data.length===0&&this.length*this.meta.components>0}slice(e,t){this.checkRange(e,t);const{components:r}=this.meta,o=this.sliceData(e*r,t*r),{validity:s,nullCount:i}=this.sliceValidity(e,t);return this.wrap(this.meta,t-e,o,s,i)}clone(){return this.assertAttached(),this.wrap(this.meta,this.length,this.copyData(),this.cloneValidity(),this.nullCountValue)}readValue(e){const{components:t}=this.meta;return t===1?this.data[e]:this.data.subarray(e*t,(e+1)*t)}fillIsDefault(){const{fill:e,default:t,components:r}=this.meta;return typeof e!="number"?!1:ju(this.dtype,r,t)===e}withDefaults(){const{components:e,default:t}=this.meta,r=this.copyData(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||Hu(this.dtype,r,s*e,e,t,this.meta.name,s);return this.wrap(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}sliceData(e,t){return zr(this.data.subarray(e,t))}copyData(){return this.data.slice()}}function Hu(n,e,t,r,o,s,i){if(typeof o=="number"){Ku(n,o,s,i),r===1?e[t]=o:e.fill(o,t,t+r);return}if(r===1||!Yu(o,r))throw new P("E_COLUMN_TYPE",`row ${i} of ${n} column "${s}" is not ${r} number(s)`,{column:s,row:i,components:r,found:typeof o});for(let a=0;a<r;a++)Ku(n,o[a],s,i);for(let a=0;a<r;a++)e[t+a]=o[a]}function Ku(n,e,t,r){if(!yr(n,e))throw new P("E_COLUMN_TYPE",`row ${r} of ${n} column "${t}": ${e} is not representable`,{column:t,row:r,value:e})}function Yu(n,e){if(typeof n!="object"||n===null)return!1;const t=n;if(t.length!==e)return!1;for(let r=0;r<e;r++)if(typeof t[r]!="number")return!1;return!0}class va extends Uo{constructor(e,t,r,o,s){super("f32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new va(e,t,r,o,s)}}class Aa extends Uo{constructor(e,t,r,o,s){super("f64",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Aa(e,t,r,o,s)}}class Ea extends Uo{constructor(e,t,r,o,s){super("i32",e,t,r,o,s)}self(){return this}wrap(e,t,r,o,s){return new Ea(e,t,r,o,s)}}class _a extends Uo{constructor(e,t,r,o,s){super("u32",e,t,r,o,s)}paddedU32View(){return this.data}self(){return this}wrap(e,t,r,o,s){return new _a(e,t,r,o,s)}}class Ia extends Uo{constructor(e,t,r,o,s){super("u8",e,t,r,o,s)}get paddedByteLength(){return Mo(this.data.byteLength)+this.validityByteLength}paddedU32View(){return q0(this.data)}self(){return this}wrap(e,t,r,o,s){return new Ia(e,t,r,o,s)}sliceData(e,t){if(e%4===0)return zr(this.data.subarray(e,t));const r=mr(t-e);return r.set(this.data.subarray(e,t)),r}copyData(){const e=mr(this.data.length);return e.set(this.data),e}}class Fo extends br{constructor(e,t,r,o,s){super("bool",e,t,o,s),this.data=r}get byteLength(){return this.data.byteLength+this.validityByteLength}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.data}paddedU32View(){return this.assertAttached(),this.data}slice(e,t){this.checkRange(e,t);const r=t-e,o=e%32===0?zr(this.data.subarray(e>>>5,(e>>>5)+Fe(r))):Lu(this.data,e,t),{validity:s,nullCount:i}=this.sliceValidity(e,t);return new Fo(this.meta,r,o,s,i)}clone(){return this.assertAttached(),new Fo(this.meta,this.length,this.data.slice(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.data.length===0}self(){return this}readValue(e){return Le(this.data,e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="boolean")throw new P("E_COLUMN_TYPE",`default of bool column "${t}" is not a boolean`,{column:t,field:"default"});const r=this.data.slice(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(e?Ht(r,s):Kt(r,s));return new Fo(this.meta,this.length,r,this.cloneValidity(),this.nullCountValue)}}class Bo extends br{constructor(e,t,r,o,s,i){super("dict",e,t,s,i),this.codeMap=null,this.codes=r,this.dictionary=o}get byteLength(){return this.codes.byteLength+this.validityByteLength}codeOf(e){this.codeMap??=Q0(this.dictionary);const t=this.codeMap.get(e);return t===void 0?x:t}mutableData(){return this.assertMutable("mutableData"),this.assertAttached(),this.codes}paddedU32View(){return this.assertAttached(),this.codes}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Bo(this.meta,t-e,zr(this.codes.subarray(e,t)),this.dictionary,r,o)}storageDetached(){return this.codes.length===0}clone(){return this.assertAttached(),new Bo(this.meta,this.length,this.codes.slice(),[...this.dictionary],this.cloneValidity(),this.nullCountValue)}self(){return this}readValue(e){return this.dictionary[this.codes[e]]}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of dict column "${t}" is not a string`,{column:t,field:"default"});let r=this.dictionary,o=this.codeOf(e);o===x&&(o=r.length,r=[...r,e]);const s=this.codes.slice(),i=this.validityWords;if(i!==null)for(let a=0;a<this.length;a++)Le(i,a)||(s[a]=o);return new Bo(this.meta,this.length,s,r,this.cloneValidity(),this.nullCountValue)}}function hy(n){const e=Do(n,n.length),t=mr(e.utf8.length);return t.set(e.utf8),{offsets:e.offsets,utf8:t}}class ln extends br{constructor(e,t,r,o,s,i,a){super("string",e,t,i,a),this.offsetsStore=r,this.utf8Store=o,this.strings=s}get offsets(){return this.store(),this.offsetsStore}get utf8(){return this.store(),this.utf8Store}get byteLength(){return this.store(),this.offsetsStore.byteLength+this.utf8Store.byteLength+this.validityByteLength}valueAt(e){const t=this.strings?.[e];if(t!==void 0)return t;this.assertAttached(),this.store();const r=this.offsetsStore,o=this.utf8Store,s=cy.decode(o.subarray(r[e],r[e+1]));return this.strings??=new Array(this.length),this.strings[e]=s,s}decodeAll(){const e=new Array(this.length);for(let t=0;t<this.length;t++)e[t]=this.valueAt(t);return e}slice(e,t){this.checkRange(e,t);const r=t-e,{validity:o,nullCount:s}=this.sliceValidity(e,t),i=this.strings===null?null:this.strings.slice(e,t);if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,r,null,null,i,o,s);const a=this.offsetsStore[e],c=new Uint32Array(r+1);for(let u=0;u<=r;u++)c[u]=this.offsetsStore[e+u]-a;const l=zr(this.utf8Store.subarray(a,this.offsetsStore[t]));return new ln(this.meta,r,c,l,i,o,s)}clone(){this.assertAttached();const e=this.strings===null?null:[...this.strings];if(this.offsetsStore===null||this.utf8Store===null)return new ln(this.meta,this.length,null,null,e,this.cloneValidity(),this.nullCountValue);const t=mr(this.utf8Store.length);return t.set(this.utf8Store),new ln(this.meta,this.length,this.offsetsStore.slice(),t,e,this.cloneValidity(),this.nullCountValue)}hasStore(){return this.offsetsStore!==null}decodedCache(){return this.strings}self(){return this}storageDetached(){return this.offsetsStore!==null&&this.offsetsStore.length===0}readValue(e){return this.valueAt(e)}fillIsDefault(){return this.meta.fill===this.meta.default}withDefaults(){const{default:e,name:t}=this.meta;if(typeof e!="string")throw new P("E_COLUMN_TYPE",`default of string column "${t}" is not a string`,{column:t,field:"default"});const r=this.decodeAll(),o=this.validityWords;if(o!==null)for(let s=0;s<this.length;s++)Le(o,s)||(r[s]=e);return new ln(this.meta,this.length,null,null,r,this.cloneValidity(),this.nullCountValue)}store(){if(this.offsetsStore!==null&&this.utf8Store!==null){this.assertAttached();return}const e=this.strings??[],t=new Array(this.length);for(let o=0;o<this.length;o++)t[o]=e[o]??"";const r=hy(t);this.offsetsStore=r.offsets,this.utf8Store=r.utf8,it(r.offsets.buffer),it(r.utf8.buffer)}}class zo extends br{constructor(e,t,r,o,s,i){super("list",e,t,s,i),this.offsets=r,this.child=o}get byteLength(){return this.offsets.byteLength+this.child.byteLength+this.validityByteLength}sliceOf(e){this.assertAttached();const t=this.offsets[e],r=this.offsets[e+1],o=new Array(r-t);for(let s=t;s<r;s++)o[s-t]=this.child.value(s);return o}slice(e,t){this.checkRange(e,t);const r=t-e,o=this.offsets[e],s=new Uint32Array(r+1);for(let c=0;c<=r;c++)s[c]=this.offsets[e+c]-o;const{validity:i,nullCount:a}=this.sliceValidity(e,t);return new zo(this.meta,r,s,this.child.slice(o,this.offsets[t]),i,a)}clone(){return this.assertAttached(),new zo(this.meta,this.length,this.offsets.slice(),this.child.clone(),this.cloneValidity(),this.nullCountValue)}storageDetached(){return this.offsets.length===0||ka(this.child)}self(){return this}readValue(e){return this.sliceOf(e)}fillIsDefault(){return!1}withDefaults(){const{default:e,name:t}=this.meta;if(!Array.isArray(e))throw new P("E_COLUMN_TYPE",`default of list column "${t}" is not an array`,{column:t,field:"default"});const r=new Array(this.length),o=this.validityWords;for(let i=0;i<this.length;i++)r[i]=o!==null&&!Le(o,i)?e:this.sliceOf(i);const s=Qu(this.meta,r);return new zo(this.meta,this.length,s.offsets,s.child,this.cloneValidity(),this.nullCountValue)}}class Go extends br{constructor(e,t,r,o,s){super("json",e,t,o,s),this.values=r}get byteLength(){return this.validityByteLength}slice(e,t){this.checkRange(e,t);const{validity:r,nullCount:o}=this.sliceValidity(e,t);return new Go(this.meta,t-e,this.values.slice(e,t),r,o)}clone(){return this.assertAttached(),new Go(this.meta,this.length,[...this.values],this.cloneValidity(),this.nullCountValue)}storageDetached(){return!1}self(){return this}readValue(e){return this.values[e]}fillIsDefault(){return!1}withDefaults(){const{default:e}=this.meta,t=[...this.values],r=this.validityWords;if(r!==null)for(let o=0;o<this.length;o++)Le(r,o)||(t[o]=e);return new Go(this.meta,this.length,t,this.cloneValidity(),this.nullCountValue)}}function gy(n){return n instanceof br}function ka(n){return n.detached}function un(n,e,t,r){return new P("E_COLUMN_LENGTH",`column "${n.name}": ${e} has length ${r}, expected ${t}`,{column:n.name,what:e,expected:t,found:r})}function dn(n,e){return new P("E_COLUMN_TYPE",`column "${n.name}": ${e}`,{column:n.name})}function Tt(n){const{meta:e,length:t}=n;if(!(Number.isInteger(t)&&t>=0))throw new P("E_COLUMN_LENGTH",`column "${e.name}": invalid row count ${t}`,{column:e.name,found:t});const{validity:r}=n;let o=null;if(r!==null){if(!e.nullable)throw dn(e,"a non-nullable column cannot carry a validity bitmap");if(!(r instanceof Uint32Array))throw dn(e,"validity must be a Uint32Array");if(r.length!==Fe(t))throw un(e,"validity",Fe(t),r.length);o=r}const s=o===null?0:t-gr(o,t),{dtype:i}=e;switch(i){case"f32":return new va(e,t,Wo(n,Float32Array),o,s);case"f64":return new Aa(e,t,Wo(n,Float64Array),o,s);case"i32":return new Ea(e,t,Wo(n,Int32Array),o,s);case"u32":return new _a(e,t,Wo(n,Uint32Array),o,s);case"u8":{const a=Wo(n,Uint8Array);if(!Ds(a))throw new P("E_COLUMN_ALIGNMENT",`column "${e.name}": no padded u32 view over the u8 data`,{column:e.name,byteOffset:a.byteOffset,byteLength:a.byteLength});return new Ia(e,t,a,o,s)}case"bool":{if(!(n.data instanceof Uint32Array))throw dn(e,"bool data must be packed Uint32Array words");if(n.data.length!==Fe(t))throw un(e,"data",Fe(t),n.data.length);return new Fo(e,t,n.data,o,s)}case"dict":{if(!(n.data instanceof Uint32Array))throw dn(e,"dict codes must be a Uint32Array");if(n.data.length!==t)throw un(e,"codes",t,n.data.length);if(n.dictionary===null)throw dn(e,"dict column needs a dictionary");return new Bo(e,t,n.data,n.dictionary,o,s)}case"string":{if(n.offsets===null||n.utf8===null){const{strings:a}=n;if(a?.length!==t)throw un(e,"strings",t,a===null?-1:a.length);for(let c=0;c<t;c++)if(typeof a[c]!="string")throw dn(e,`row ${c} is not a decoded string and no Utf8 store is present`);return new ln(e,t,null,null,a,o,s)}if(n.offsets.length!==t+1)throw un(e,"offsets",t+1,n.offsets.length);if(n.offsets[t]!==n.utf8.length)throw un(e,"utf8",n.offsets[t],n.utf8.length);return new ln(e,t,n.offsets,n.utf8,n.strings,o,s)}case"list":{if(n.offsets?.length!==t+1)throw un(e,"offsets",t+1,n.offsets===null?-1:n.offsets.length);const{child:a}=n;if(a===null||a.dtype==="list")throw dn(e,"list column needs a non-list child column");if(a.validity!==null||a.meta.nullable)throw dn(e,"list child must be non-nullable");if(a.dtype!==e.itemDtype||a.meta.components!==e.itemComponents)throw dn(e,`list child is ${a.dtype} x${a.meta.components}, declared ${String(e.itemDtype)} x${String(e.itemComponents)}`);if(n.offsets[t]!==a.length)throw un(e,"child",n.offsets[t],a.length);return new zo(e,t,n.offsets,a,o,s)}case"json":{if(n.values?.length!==t)throw un(e,"values",t,n.values===null?-1:n.values.length);return new Go(e,t,n.values,o,s)}default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}function Wo(n,e){const{meta:t,length:r}=n;if(!(n.data instanceof e))throw dn(t,`${t.dtype} data must be a ${e.name}`);const o=r*t.components;if(n.data.length!==o)throw un(t,"data",o,n.data.length);return n.data}function Us(n){const e={meta:n.meta,length:n.length,data:null,validity:n.validity,nullCount:n.nullCount,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null},{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return e.data=n.data,e;case"dict":return e.data=n.codes,e.dictionary=n.dictionary,e;case"string":return n instanceof ln?(e.strings=n.decodedCache(),n.hasStore()&&(e.offsets=n.offsets,e.utf8=n.utf8),e):(e.offsets=n.offsets,e.utf8=n.utf8,e);case"list":return e.offsets=n.offsets,e.child=n.child,e;case"json":return e.values=n.values,e;default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function Sa(n){const e=new Set,t=r=>{r!==null&&e.add(r.buffer)};switch(t(n.validity),n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":t(n.data);break;case"dict":t(n.codes);break;case"string":(!(n instanceof ln)||n.hasStore())&&(t(n.offsets),t(n.utf8));break;case"list":t(n.offsets);for(const r of Sa(n.child))e.add(r);break;case"json":break;default:{const r=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${r.dtype}`,{})}}return[...e]}function Xu(n,e){const t=n.meta;if(e.dtype!==t.dtype||e.components!==t.components||e.itemDtype!==t.itemDtype||e.itemComponents!==t.itemComponents)throw new P("E_COLUMN_TYPE",`column "${t.name}" is ${t.dtype} x${t.components}; a patch cannot change its dtype`,{column:t.name,field:"dtype"});if(e.fill!==t.fill)throw new P("E_COLUMN_TYPE",`the fill of existing column "${t.name}" cannot change`,{column:t.name,field:"fill"});const r=Us(n);if(!e.nullable&&n.validity!==null){if(n.nullCount>0)throw new P("E_COLUMN_TYPE",`column "${t.name}" has ${n.nullCount} unset rows and cannot become non-nullable`,{column:t.name,field:"nullable",nullCount:n.nullCount});r.validity=null}return r.meta=e,Tt(r)}function wy(n){Ms.delete(n)}function py(n){const{dtype:e}=n;switch(e){case"f32":case"i32":case"u32":case"bool":return n.data;case"u8":return n.paddedU32View();case"dict":return n.codes;case"f64":{let t=Ms.get(n);return t===void 0&&(t=new Float32Array(n.data),Ms.set(n,t)),t}case"string":case"list":case"json":throw new P("E_GPU_INELIGIBLE",`a ${e} column cannot be bound by the GPU`,{column:n.meta.name,dtype:e});default:{const t=e;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function my(n,e,t){const r=typeof e=="string"?e:"",o=n.codeOf(r);return o===x?0:o}function Pa(n){const e=new J0(n.options===null?void 0:n.options);return typeof n.fill=="string"&&n.fill!==""&&e.intern(n.fill),e}function Gr(n,e,t){return{meta:n,length:e,data:null,validity:t,nullCount:t===null?0:e,dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null}}function yy(n){if(n.itemDtype===null||n.itemComponents===null)throw new P("E_COLUMN_TYPE",`column "${n.name}" is not a list`,{column:n.name,field:"itemDtype"});return ht(`${n.name}.item`,n.domain,{dtype:n.itemDtype,components:n.itemComponents,nullable:!1,refersTo:n.refersTo??void 0})}function by(n,e){return n===void 0||n===null&&e!=="json"}function Qu(n,e){const t=new Uint32Array(e.length+1),r=[];for(let s=0;s<e.length;s++){for(const i of e[s])r.push(i);t[s+1]=r.length}const o=Vo(yy(n),r);return{offsets:t,child:o}}function Vo(n,e){const{length:t}=e,{dtype:r,components:o,fill:s,name:i}=n;let a=null,c=0;for(let d=0;d<t;d++)if(by(e[d],r)){if(!n.nullable)throw new P("E_COLUMN_TYPE",`row ${d} of non-nullable column "${i}" is unset`,{column:i,row:d});a??=In(t,!0),Kt(a,d),c++}const l=Gr(n,t,a);l.nullCount=c;const u=d=>a===null||Le(a,d);switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const d=Ju(r,t*o);s!==0&&d.fill(s);for(let f=0;f<t;f++){if(!u(f))continue;const h=e[f],g=typeof h=="boolean"?Number(h):h;Hu(r,d,f*o,o,g,i,f)}l.data=d;break}case"bool":{const d=In(t,s===!0);for(let f=0;f<t;f++){if(!u(f))continue;Br(e[f],"bool")===!0?Ht(d,f):Kt(d,f)}l.data=d;break}case"dict":{const d=Pa(n),f=new Uint32Array(t);a!==null&&f.fill(my(d,s));for(let h=0;h<t;h++){if(!u(h))continue;const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of dict column "${i}" is not a string`,{column:i,row:h});f[h]=d.intern(g)}l.data=f,l.dictionary=d.values;break}case"string":{const d=typeof s=="string"?s:"",f=new Array(t);for(let h=0;h<t;h++){if(!u(h)){f[h]=d;continue}const g=Br(e[h],"string");if(typeof g!="string")throw new P("E_COLUMN_TYPE",`row ${h} of string column "${i}" is not a string`,{column:i,row:h});wr(g,{column:i,row:h}),f[h]=g}l.strings=f;break}case"list":{const d=new Array(t);for(let h=0;h<t;h++){if(!u(h)){d[h]=[];continue}const g=e[h];if(!Array.isArray(g))throw new P("E_COLUMN_TYPE",`row ${h} of list column "${i}" is not an array`,{column:i,row:h});d[h]=g}const f=Qu(n,d);l.offsets=f.offsets,l.child=f.child;break}case"json":{const d=new Array(t);for(let f=0;f<t;f++){if(!u(f)){d[f]=void 0;continue}cn(e[f],`row ${f}`),d[f]=e[f]}l.values=d;break}default:{const d=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${d}`,{dtype:d})}}return Tt(l)}function Ju(n,e){switch(n){case"f32":return new Float32Array(e);case"f64":return new Float64Array(e);case"i32":return new Int32Array(e);case"u32":return new Uint32Array(e);case"u8":return mr(e);default:{const t=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${t}`,{dtype:t})}}}function vy(n){let e=!1,t=!1;for(const r of n)r!=null&&(Array.isArray(r)?e=!0:t=!0);return e&&!t?{dtype:"list",itemDtype:Bu(Ay(n))??"json"}:{dtype:Bu(n)??"json",itemDtype:void 0}}function Ay(n){const e=[];for(const t of n)if(Array.isArray(t))for(const r of t)e.push(r);return e}function xa(n,e,t,r,o){if(r.length!==e)throw new P("E_COLUMN_LENGTH",`column "${t}": ${r.length} values for ${e} rows`,{column:t,expected:e,found:r.length});let s={nullable:!0,...o};if(s.dtype===void 0){const a=vy(r);s={...s,dtype:a.dtype},a.dtype==="list"&&s.itemDtype===void 0&&(s={...s,itemDtype:a.itemDtype})}const i=ht(t,n,s);return Vo(i,r)}function Zu(n){return n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":n instanceof Int32Array?"i32":n instanceof Uint32Array?"u32":"u8"}function Ey(n,e,t,r,o,s="copy"){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=ht(t,n,{nullable:!1,...o,dtype:a}),u=Gr(l,e,null),d=_y(t,a,e,l.components);if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});if(!pa(r)){const h=r.buffer instanceof ArrayBuffer?"resizable ArrayBuffer":"SharedArrayBuffer";throw new P("E_UNSUPPORTED",`column "${t}": a view over a ${h} cannot be adopted`,{column:t,reason:h})}let f=r;if(r instanceof Uint8Array&&!Ds(r)){if(s==="strict")throw new P("E_COLUMN_ALIGNMENT",`column "${t}": no zero-copy padded u32 view over the u8 array`,{column:t,byteOffset:r.byteOffset,byteLength:r.byteLength,bufferByteLength:r.buffer.byteLength});const h=mr(r.length);h.set(r),f=h}return u.data=f,a==="dict"&&(u.dictionary=Iy(l,r,e)),Tt(u)}function _y(n,e,t,r){switch(e){case"bool":return Fe(t);case"dict":return t;case"f32":case"f64":case"i32":case"u32":case"u8":return t*r;default:{const o=e;throw new P("E_COLUMN_TYPE",`column "${n}": a ${o} column cannot adopt a typed array`,{column:n,field:"dtype"})}}}function Iy(n,e,t){const{name:r}=n,o=Pa(n);for(let s=0;s<t;s++){const i=e[s];if(i>=o.size)throw new P("E_COLUMN_TYPE",`column "${r}": code ${i} at row ${s} is outside the ${o.size} declared options`,{column:r,row:s,code:i})}return o.values}function zt(n,e,t){if(e!==void 0){if(typeof e!="string"||!t.includes(e))throw new P("E_UNSUPPORTED",`option ${n} has an unsupported value ${ky(e)}`,{field:n,found:e,reason:"unsupported option"});return e}}function ky(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):`a ${typeof n}`}const Fs=["first","last","sum","min","max"],Sy=[...Fs,"mean","count","drop"];function Pn(n){if(typeof n=="number")return String(n);if(typeof n=="string"){const e=n.length>40?`${n.slice(0,37)}...`:n;return JSON.stringify(e)}return n===null?"null":typeof n=="bigint"?`${String(n)}n`:`a value of type ${typeof n}`}function jn(n){if(typeof n=="number"){if(!Number.isFinite(n))throw new P("E_INVALID_ID",`invalid node id ${String(n)}: not a finite number`,{id:n,reason:"non-finite"});return n===0?0:n}if(typeof n=="string"){if(Pu(n))throw new P("E_INVALID_ID",`invalid node id ${Pn(n)}: lone surrogate`,{id:n,reason:"lone surrogate"});return n}throw new P("E_INVALID_ID",`invalid node id: ${Pn(n)} is not a string or a number`,{reason:"unsupported type",type:typeof n})}const Bs=new WeakMap;function Py(n){const e=Bs.get(n);if(e===void 0)throw new P("E_UNSUPPORTED","not a NodeIdMap of this package",{reason:"foreign id map"});return e}function fn(n,e,t={}){return{kind:n,size:e,offset:0,denseValues:null,denseInverse:null,decoded:null,numbers:null,tags:null,strings:null,map:null,stringIndex:null,...t}}function ed(n){return n.size===0?!1:n.denseValues!==null&&n.denseValues.length===0||n.decoded===null&&n.numbers!==null&&n.numbers.length===0||n.decoded===null&&n.tags!==null&&n.tags.length===0||n.decoded===null&&n.strings?.detached===!0}function xy(n){const e=Bs.get(n);return e!==void 0&&ed(e)}function jo(n){return n===0?0:n}function Ca(n,e,t){return new P("E_DUPLICATE_ID",`duplicate node id ${Pn(n)} at indices ${e} and ${t}`,{id:n,indices:[e,t]})}function Wr(n,e){return new P("E_INVALID_SNAPSHOT",`id map violates invariant I11: ${n}`,{invariant:"I11",reason:n,...e})}function hn(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function td(n,e,t){const r=new Uint32Array(e+1).fill(x);for(let o=0;o<n.length;o++){const s=n[o];if(r[s]!==x)throw t(s,r[s],o);r[s]=o}return r}function qo(n,e,t){const r=new Map;for(let o=0;o<e;o++){const s=n[o],i=r.get(s);if(i!==void 0)throw t(s,i,o);r.set(s,o)}return r}function Cy(n,e){let t=!0,r=!0,o=!0,s=-1,i=0,a=!0;if(e>0){const c=n[0];typeof c=="number"&&Number.isSafeInteger(c)?i=c:a=!1}for(let c=0;c<e;c++){const l=n[c];typeof l=="number"?(r=!1,a&&l!==c+i&&(a=!1),o&&(Number.isInteger(l)&&l>=0&&l<Te?l>s&&(s=l):o=!1)):(t=!1,a=!1,o=!1)}return t||(s=-1),{allNumbers:t,allStrings:r,identity:a,offset:i,allDenseIntegers:o,maxId:s}}function Ny(n,e){return e===0||n.identity?"identity":n.allDenseIntegers&&n.maxId+1<=2*e?"dense":n.allNumbers?"numeric":n.allStrings?"string":"mixed"}function Ty(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++){const o=n[r];t[r]=typeof o=="number"?o:x}return t}class Yt{constructor(e){this.kind=e.kind,this.size=e.size,this.offset=e.kind==="identity"?e.offset:0,this.storage=e,Bs.set(this,e),Object.freeze(this)}idOf(e){if(!(e>=0&&e<this.size)||!Number.isInteger(e))throw new P("E_INDEX_RANGE",`node index ${e} out of range (size ${this.size})`,{index:e,size:this.size});return this.idAt(e)}indexOf(e){const{storage:t}=this;switch(t.kind){case"identity":{if(typeof e!="number")return x;const r=e-t.offset;return!Number.isInteger(r)||r<0||r>=t.size?x:r===0?0:r}case"dense":{const r=t.denseInverse;return typeof e!="number"||!Number.isInteger(e)||e<0||e>=r.length?x:r[e]}case"numeric":case"string":case"mixed":{const r=this.reverseMap().get(e);return r===void 0||r>=t.size?x:r}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}has(e){return this.indexOf(e)!==x}requireIndex(e){const t=this.indexOf(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return t}indicesOf(e,t="invalid"){zt("onMissing",t,["invalid","throw"]);const r=t==="throw"?i=>this.requireIndex(i):i=>this.indexOf(i);if(Array.isArray(e)){const i=e,a=new Uint32Array(i.length);for(let c=0;c<i.length;c++)a[c]=r(i[c]);return a}let o=new Uint32Array(16),s=0;for(const i of e){if(s===o.length){const a=new Uint32Array(o.length*2);a.set(o),o=a}o[s++]=r(i)}return o.slice(0,s)}idsSlice(e=0,t=this.size){const[r,o]=Cu(e,t,this.size),{storage:s}=this;switch(this.assertAttached(),s.kind){case"identity":{const i=new Array(o-r);for(let a=r;a<o;a++)i[a-r]=a+s.offset;return i}case"dense":return Array.from(s.denseValues.subarray(r,o));case"numeric":return s.decoded!==null?s.decoded.slice(r,o):Array.from(s.numbers.subarray(r,o),jo);case"string":return s.strings.slice(r,o);case"mixed":{if(s.decoded!==null)return s.decoded.slice(r,o);const i=s.tags,a=s.numbers,c=s.strings,l=new Array(o-r);for(let u=r;u<o;u++)l[u-r]=i[u]===0?jo(a[u]):c.at(u);return l}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(s.kind)}`,{kind:s.kind})}}toArray(){return this.idsSlice(0,this.size)}*[Symbol.iterator](){for(let e=0;e<this.size;e++)yield this.idAt(e)}toMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(this.idAt(r),e[r]);return t}toStringMap(e){const t=new Map;for(let r=0;r<this.size;r++)t.set(String(this.idAt(r)),e[r]);return t}toRecord(e){const t=Object.create(null);for(let r=0;r<this.size;r++)t[String(this.idAt(r))]=e[r];return t}*entries(e){for(let t=0;t<this.size;t++)yield[this.idAt(t),e[t]]}stringIndex(){const{storage:e}=this;if(e.stringIndex===null){const t=new Map;for(let r=0;r<e.size;r++){const o=this.idAt(r),s=String(o);(typeof o=="string"||!t.has(s))&&t.set(s,r)}e.stringIndex=t}return e.stringIndex}byteLength(){const{storage:e}=this;let t=0;return e.denseValues!==null&&(t+=e.denseValues.byteLength),e.denseInverse!==null&&(t+=e.denseInverse.byteLength),e.numbers!==null&&(t+=e.numbers.byteLength),e.tags!==null&&(t+=e.tags.byteLength),e.strings!==null&&(t+=e.strings.byteLength()),t}idAt(e){const{storage:t}=this;switch(this.assertAttached(),t.kind){case"identity":return e+t.offset;case"dense":return t.denseValues[e];case"numeric":return t.decoded!==null?t.decoded[e]:jo(t.numbers[e]);case"string":return t.strings.at(e);case"mixed":return t.decoded!==null?t.decoded[e]:t.tags[e]===0?jo(t.numbers[e]):t.strings.at(e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t.kind)}`,{kind:t.kind})}}assertAttached(){if(ed(this.storage))throw new P("E_DETACHED","the id map's storage was transferred away",{kind:this.storage.kind})}reverseMap(){const{storage:e}=this;if(e.map===null){this.assertAttached(),e.decoded===null&&e.strings!==null&&e.strings.materialiseDecoded();const t=new Map;for(let r=0;r<e.size;r++)t.set(this.idAt(r),r);e.map=t}return e.map}}function nd(n,e=0){if(!Number.isInteger(n)||n<0||n>Te)throw new P("E_TOO_LARGE",`node count ${n} is not an integer in [0, MAX_COUNT]`,{count:n,max:Te});if(!Number.isSafeInteger(e))throw new P("E_INVALID_ID",`identity offset ${e} is not a safe integer`,{offset:e,reason:"non-integer offset"});return new Yt(fn("identity",n,{offset:e}))}function rd(n,e=n.length,t={}){if(!Number.isInteger(e)||e<0||e>Te)throw new P("E_TOO_LARGE",`node count ${e} is not an integer in [0, MAX_COUNT]`,{count:e,max:Te});const r=t.map!==void 0||t.validate===!1;let o=n;if(!r){const a=new Array(e);for(let c=0;c<e;c++)a[c]=jn(n[c]);o=a}const s=Cy(o,e),i=Ny(s,e);switch(i){case"identity":return new Yt(fn("identity",e,{offset:e===0?0:s.offset}));case"dense":{const a=Ty(o,e),c=td(a,s.maxId,Ca);return new Yt(fn("dense",e,{denseValues:a,denseInverse:c}))}case"numeric":case"mixed":{const a=t.map??(r?null:qo(o,e,Ca));return new Yt(fn(i,e,{decoded:o,map:a}))}case"string":{const a=t.map??(r?null:qo(o,e,Ca)),c=Wn.fromStrings(o,e);return new Yt(fn("string",e,{strings:c,map:a}))}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(i)}`,{kind:i})}}function Oy(n){const e=Bs.get(n),t=new Set;if(e===void 0)return[];for(const r of[e.denseValues,e.denseInverse,e.numbers,e.tags])r!==null&&t.add(r.buffer);return e.strings?.encoded&&(t.add(e.strings.offsets.buffer),t.add(e.strings.utf8.buffer)),[...t]}function $y(n,e="structure"){const{kind:t,size:r}=n;if(e!=="none"&&(!Number.isInteger(r)||r<0||r>Te))throw hn("ids.size",`size ${r} is not an integer in [0, MAX_COUNT]`,{found:r});switch(t){case"identity":return Ry(n,e);case"dense":return Dy(n,e);case"numeric":return Ly(n,e);case"string":return My(n,e);case"mixed":return By(n,e);default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Na(n,e,t){return Wr(`duplicate id ${Pn(n)}`,{id:n,indices:[e,t]})}function zs(n,e,t,r){if(t!==r)throw hn(n,`expected ${r} ${e}, found ${t}`,{expected:r,found:t})}function od(n){const e=n.firstMalformedRow();if(e!==-1)throw Wr(`malformed UTF-8 in id at index ${e}`,{index:e})}function Ry(n,e){const{offset:t,size:r}=n;if(!Number.isSafeInteger(t)||r>0&&!Number.isSafeInteger(t+r-1)){const o=`offset ${t} with ${r} ids leaves the safe-integer range`;throw e==="full"?Wr(o,{found:t,size:r}):hn("ids.offset",o,{found:t,size:r})}return new Yt(fn("identity",r,{offset:jo(t)}))}function Dy(n,e){const{values:t,size:r}=n;if(!(t instanceof Uint32Array))throw hn("ids.values","a dense id map needs u32 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=-1;for(let i=0;i<t.length;i++)t[i]>o&&(o=t[i]);if(o>=Te)throw hn("ids.values",`dense id ${o} is not below MAX_COUNT`,{found:o});if(o+1>2*Math.max(r,t.length))throw hn("ids.values",`dense bound violated: max id ${o} with ${r} nodes`,{maxId:o,size:r});const s=td(t,o,(i,a,c)=>Wr(`duplicate id ${i}`,{id:i,indices:[a,c]}));return new Yt(fn("dense",r,{denseValues:t,denseInverse:s}))}function Ly(n,e){const{values:t,size:r}=n;if(!(t instanceof Float64Array))throw hn("ids.values","a numeric id map needs f64 values");e!=="none"&&zs("ids.values","values",t.length,r);let o=null;if(e==="full"){for(let s=0;s<r;s++)if(!Number.isFinite(t[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:t[s]});o=qo(t,r,Na)}return new Yt(fn("numeric",r,{numbers:t,map:o}))}function My(n,e){const{offsets:t,utf8:r,size:o}=n;if(t===null||r===null)throw hn("ids.offsets","a string id map needs offsets and utf8");e!=="none"&&ha(t,r,o,"ids.offsets");const s=Wn.fromEncoded(t,r);let i=null;return e==="full"&&(od(s),i=qo(s.decodeAll(),o,Na)),new Yt(fn("string",o,{strings:s,map:i}))}function Uy(n,e,t,r,o){zs("ids.tags","tags",n.length,o),zs("ids.numbers","numbers",e.length,o);for(let s=0;s<o;s++)if(n[s]>1)throw hn("ids.tags",`tag ${n[s]} at index ${s} is not 0 or 1`,{index:s,found:n[s]});ha(t,r,o,"ids.offsets")}function Fy(n,e,t,r){const o=new Array(r);for(let s=0;s<r;s++)if(n[s]===0){if(!Number.isFinite(e[s]))throw Wr(`non-finite id at index ${s}`,{index:s,id:e[s]});o[s]=e[s]}else o[s]=t.at(s);return o}function By(n,e){const{tags:t,numbers:r,offsets:o,utf8:s,size:i}=n;if(t===null||r===null||o===null||s===null)throw hn("ids.tags","a mixed id map needs tags, numbers, offsets and utf8");e!=="none"&&Uy(t,r,o,s,i);const a=Wn.fromEncoded(o,s);let c=null;return e==="full"&&(od(a),c=qo(Fy(t,r,a,i),i,Na)),new Yt(fn("mixed",i,{tags:t,numbers:r,strings:a,map:c}))}function zy(n){const e=Py(n),{kind:t,size:r}=e;switch(t){case"identity":return{kind:t,size:r,offset:e.offset,values:null,tags:null,numbers:null,offsets:null,utf8:null};case"dense":return{kind:t,size:r,offset:0,values:e.denseValues,tags:null,numbers:null,offsets:null,utf8:null};case"numeric":{if(e.numbers===null){const o=e.decoded,s=new Float64Array(r);for(let i=0;i<r;i++){const a=o[i];if(typeof a!="number")throw new P("E_INVALID_ID",`numeric id map holds a ${typeof a} at index ${i}`,{index:i,found:typeof a});s[i]=a}e.numbers=s,it(s.buffer)}return{kind:t,size:r,offset:0,values:e.numbers,tags:null,numbers:null,offsets:null,utf8:null}}case"string":{const o=e.strings;return{kind:t,size:r,offset:0,values:null,tags:null,numbers:null,offsets:o.offsets,utf8:o.utf8}}case"mixed":{if(e.tags===null||e.numbers===null||e.strings===null){const o=e.decoded,s=new Uint8Array(r),i=new Float64Array(r);for(let l=0;l<r;l++){const u=o[l];typeof u=="number"?i[l]=u:s[l]=1}const{offsets:a,utf8:c}=Do(o,r);e.tags=s,e.numbers=i,e.strings=Wn.fromEncoded(a,c);for(const l of[s.buffer,i.buffer,a.buffer,c.buffer])it(l)}return{kind:t,size:r,offset:0,values:null,tags:e.tags,numbers:e.numbers,offsets:e.strings.offsets,utf8:e.strings.utf8}}default:throw new P("E_UNSUPPORTED",`unknown id map kind ${String(t)}`,{kind:t})}}function Gy(n,e){const t=e.length,r=new Array(t);for(let o=0;o<t;o++)r[o]=n.idOf(e[o]);return rd(r,t,{validate:!1})}const Wy=new Set(["string","integer","mixed"]),Vy=new Set(["integer","double","date","dateTime"]),jy=new Set(["interval","timestamp"]),qy=new Set(["static","dynamic","slice"]),Ta=Object.freeze({name:null,description:null,creator:null,created:null,modified:null,keywords:Object.freeze([]),sourceFormat:null,sourceVersion:null,idType:null,timeFormat:null,timeRepresentation:null,mode:null,declaredMultigraph:null,weightOrigin:null,extra:Object.freeze({})});function Vr(n,e){return new P("E_COLUMN_TYPE",`meta.${n} has an unsupported value`,{field:n,found:typeof e})}function vr(n,e){if(e===null||typeof e=="string")return e;throw Vr(n,e)}function Gs(n,e,t){if(e===null)return null;if(typeof e=="string"&&t.has(e))return e;throw Vr(n,e)}function Hy(n){if(n===null)return null;if(typeof n!="object")throw Vr("weightOrigin",n);const e=n,t=r=>{const o=e[r];if(o==null)return null;if(typeof o!="string")throw Vr(`weightOrigin.${r}`,o);return o};return Object.freeze({format:t("format"),id:t("id"),title:t("title"),type:t("type"),namespace:t("namespace")})}function Ky(n,e){const t=(r,o)=>{const s=e[r];return s===void 0?n[r]:o(s)};return Object.freeze({name:t("name",r=>vr("name",r)),description:t("description",r=>vr("description",r)),creator:t("creator",r=>vr("creator",r)),created:t("created",r=>vr("created",r)),modified:t("modified",r=>vr("modified",r)),keywords:t("keywords",r=>{if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw Vr("keywords",r);return Object.freeze([...r])}),sourceFormat:t("sourceFormat",r=>vr("sourceFormat",r)),sourceVersion:t("sourceVersion",r=>vr("sourceVersion",r)),idType:t("idType",r=>Gs("idType",r,Wy)),timeFormat:t("timeFormat",r=>Gs("timeFormat",r,Vy)),timeRepresentation:t("timeRepresentation",r=>Gs("timeRepresentation",r,jy)),mode:t("mode",r=>Gs("mode",r,qy)),declaredMultigraph:t("declaredMultigraph",r=>{if(r===null||typeof r=="boolean")return r;throw Vr("declaredMultigraph",r)}),weightOrigin:t("weightOrigin",r=>Hy(r)),extra:t("extra",r=>ht("meta","graph",{dtype:"json",extra:r}).extra)})}const Yy=4294967295;class bt{constructor(e,t){this.used=0,this.ctor=e,this.resizable=t?.resizable??ga,this.backing=this.allocate(t?.capacity??0)}get length(){return this.used}get capacity(){return this.backing.length}get array(){return this.backing}push(e){const t=this.used;return t>=this.backing.length&&(this.backing=$u(this.backing,this.ctor,t+1,this.resizable)),this.backing[t]=e,this.used=t+1,t}pushAll(e){const t=this.used,r=t+e.length;return this.ensureCapacity(r),this.backing.set(e,t),this.used=r,t}get(e){return this.backing[e]}set(e,t){this.backing[e]=t}ensureCapacity(e){e>this.backing.length&&(this.backing=$u(this.backing,this.ctor,e,this.resizable))}resize(e,t=0){e>this.used&&(this.ensureCapacity(e),this.backing.fill(t,this.used,e)),this.used=e}view(){return new this.ctor(this.backing.buffer,0,this.used)}trim(){const e=new this.ctor(new ArrayBuffer(this.used*this.ctor.BYTES_PER_ELEMENT),0,this.used);return e.set(this.view()),e}clear(){this.used=0}release(){this.used=0,this.backing=this.allocate(0)}allocate(e){const t=this.ctor.BYTES_PER_ELEMENT,r=e===0?0:Tu(Lo(e,wa),t);return new this.ctor(Ou(r,this.resizable),0,r/t)}}class xn{constructor(e){this.bits=0,this.words=new bt(Uint32Array,{capacity:Fe(e?.capacity??0),resizable:e?.resizable})}get length(){return this.bits}push(e){const t=this.bits;return t%32===0&&this.words.push(0),e&&ba(this.words.array,t,!0),this.bits=t+1,t}get(e){return Le(this.words.array,e)}set(e,t){ba(this.words.array,e,t)}count(){return gr(this.words.array,this.bits)}resize(e,t=!1){const r=this.bits;this.words.resize(Fe(e),0),e<r?ya(this.words.array,e):t&&e>r&&this.setRange(r,e),this.bits=e}setRange(e,t){const{array:r}=this.words;let o=e;for(;o<t&&o%32!==0;)Ht(r,o++);const s=t-t%32;for(o<s&&(r.fill(Yy,o/32,s/32),o=s);o<t;)Ht(r,o++)}view(){return this.words.view()}trim(){return this.words.trim()}clear(){this.bits=0,this.words.clear()}release(){this.bits=0,this.words.release()}}const Xy=Object.freeze([]),Oa=2**24;function $a(n){if(n>Oa)throw new P("E_TOO_LARGE",`node count ${n} exceeds the ${Oa} nodes with explicit ids one builder can hold`,{count:n,max:Oa})}function gn(n,e,t,r){return new P("E_COLUMN_TYPE",`row ${e} of ${n.dtype} column "${n.name}": ${t}`,{column:n.name,domain:n.domain,row:e,found:r})}function Ra(n){const e=Ls(n);if(e===null)throw new P("E_COLUMN_TYPE","an unset value cannot start an inferred column",{reason:"unset"});return e}function Da(n){switch(n){case"bool":return"bool";case"i32":case"u8":return"i32";case"u32":case"f32":case"f64":return"f64";case"dict":case"string":return"string";case"list":case"json":return"json";default:{const e=n;throw new P("E_COLUMN_TYPE",`unknown dtype ${e}`,{dtype:e})}}}function Qy(n,e,t){const r=n.itemDtype,o=n.itemComponents??1;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":Jy(n,e,t,r,o);return;case"bool":if(typeof t!="boolean")throw gn(n,e,"list item is not a boolean",typeof t);return;case"dict":case"string":if(typeof t!="string")throw gn(n,e,"list item is not a string",typeof t);wr(t,{column:n.name,row:e});return;case"json":cn(t,n.name);return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Jy(n,e,t,r,o){if(o===1){if(typeof t!="number"||!yr(r,t))throw gn(n,e,`list item is not a representable ${r}`,typeof t);return}if(!Array.isArray(t)||t.length!==o)throw gn(n,e,`list item is not ${o} numbers`,typeof t);for(const s of t)if(typeof s!="number"||!yr(r,s))throw gn(n,e,`list item component is not a representable ${r}`,typeof s)}class Ws{constructor(e,t,r,o){this.length=0,this.typed=null,this.bits=null,this.values=null,this.dictionary=null,this.validity=null,this.meta=e,this.resizable=r,t?(this.inferrer=new zu,this.inferrer.widenTo(Da(e.dtype))):this.inferrer=null,this.allocate(o)}get inferred(){return this.inferrer!==null}get inferredDtype(){return this.inferrer===null?null:this.inferrer.dtype}ensureLength(e){if(e<=this.length)return;const{meta:t}=this;if(this.typed!==null)this.typed.resize(e*t.components,this.fillNumber());else if(this.bits!==null)this.bits.resize(e,t.fill===!0);else if(this.values!==null){const r=this.fillValue();for(let o=this.length;o<e;o++)this.values.push(r)}this.validity!==null&&this.validity.resize(e,!1),this.length=e}isSet(e){return e>=this.length?!1:this.validity===null||this.validity.get(e)}write(e,t){if(this.ensureLength(e+1),t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json"))return this.unset(e),null;let r=null;if(this.inferrer!==null){const o=this.meta.dtype;if(this.inferrer.observeValue(t)){const s=this.inferrer.dtype;this.widenTo(s),r={from:o,to:s}}this.storeRaw(e,t)}else this.store(e,t);return this.validity!==null&&this.validity.set(e,!0),r}checkValue(e,t){if(t===void 0||t===null&&(this.inferrer!==null||this.meta.dtype!=="json")){if(this.validity===null)throw this.unsetError(e);return}if(this.inferrer!==null){Ls(t),this.checkRaw(e,t);return}this.coerce(e,t)}unset(e){if(this.ensureLength(e+1),this.validity===null)throw this.unsetError(e);this.validity.set(e,!1),this.writeFill(e)}unsetError(e){return new P("E_COLUMN_TYPE",`row ${e} of non-nullable column "${this.meta.name}" cannot be unset`,{column:this.meta.name,row:e,field:"nullable"})}read(e){if(!this.isSet(e))return;if(this.inferrer!==null)return Br(this.values[e],this.inferrer.dtype);const{meta:t}=this,{dtype:r,components:o}=t;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(o===1)return s.get(e);const i=new Array(o);for(let a=0;a<o;a++)i[a]=s.get(e*o+a);return i}case"bool":return this.bits.get(e);case"dict":{const s=this.typed.get(e);return this.dictionary.values[s]}case"string":case"list":case"json":return this.values[e];default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}widenTo(e){const{meta:t}=this,r=ht(t.name,t.domain,{dtype:e,nullable:!0,role:t.role??void 0,extra:t.extra});if(this.inferrer!==null){this.inferrer.widenTo(e),this.meta=r;return}const o=this.length,s=new Array(o),i=new xn({capacity:o,resizable:this.resizable});i.resize(o,!1);for(let a=0;a<o;a++)this.isSet(a)&&(s[a]=this.read(a),i.set(a,!0));this.meta=r,this.inferrer=new zu,this.inferrer.widenTo(e),this.typed=null,this.bits=null,this.dictionary=null,this.values=s,this.validity=i}gather(e,t){const r=e===null?this.length:e.length,o=new Ws(this.meta,this.inferred,this.resizable,this.dictionary??void 0);o.ensureLength(r);const{components:s}=this.meta,i=t!==null&&this.meta.refersTo!==null;for(let a=0;a<r;a++){const c=e===null?a:e[a];if(this.isSet(c)){if(o.typed!==null&&this.typed!==null)if(i){const l=sd(this.typed.get(c),t);if(l===x){o.unsetDangling(a);continue}o.typed.set(a,l)}else for(let l=0;l<s;l++)o.typed.set(a*s+l,this.typed.get(c*s+l));else if(o.bits!==null&&this.bits!==null)o.bits.set(a,this.bits.get(c));else if(o.values!==null&&this.values!==null){let l=this.values[c];if(i){const u=l,d=[];for(const f of u){const h=sd(f,t);h!==x&&d.push(h)}if(d.length===0&&u.length>0){o.unsetDangling(a);continue}l=d}o.values[a]=l}o.validity!==null&&o.validity.set(a,!0)}}return o}unsetDangling(e){if(this.validity!==null)return;const{meta:t}=this;this.meta=ht(t.name,t.domain,{...Sn(t),nullable:!0});const r=new xn({capacity:this.length,resizable:this.resizable});r.resize(this.length,!1);const{typed:o}=this;for(let s=0;s<e;s++)o?.get(s)!==x&&r.set(s,!0);this.validity=r}toColumn(e){this.ensureLength(e);const{meta:t}=this,{dtype:r,components:o}=t;if(this.inferrer!==null){const a=this.values,c=new Array(e);for(let l=0;l<e;l++)c[l]=this.isSet(l)?a[l]:void 0;return Vo(t,c)}let s=null;this.validity!==null&&this.validity.count()!==e&&(s=this.validity.trim());const i={meta:t,length:e,data:null,validity:s,nullCount:s===null?0:e-this.validity.count(),dictionary:null,offsets:null,utf8:null,strings:null,child:null,values:null};switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const a=Ju(r,e*o);return a.set(this.typed.view().subarray(0,e*o)),i.data=a,t.refersTo!==null&&this.validity===null&&Zy(i,a,e),Tt(i)}case"bool":return i.data=this.bits.trim(),Tt(i);case"dict":{const a=new Uint32Array(e);return a.set(this.typed.view().subarray(0,e)),i.data=a,i.dictionary=[...this.dictionary.values],Tt(i)}case"string":case"list":case"json":{const a=this.values,c=new Array(e);for(let l=0;l<e;l++){const u=this.isSet(l)?a[l]:void 0;c[l]=u===void 0?this.unsetEntry():u}return Vo(t,c)}default:{const a=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${a}`,{dtype:a})}}}byteLength(){let e=0;return this.typed!==null&&(e+=this.typed.array.byteLength),this.bits!==null&&(e+=Fe(this.bits.length)*4),this.validity!==null&&(e+=Fe(this.validity.length)*4),e}allocate(e){const{meta:t}=this,{dtype:r}=t,o={resizable:this.resizable};if(this.inferrer!==null){this.values=[],this.validity=new xn(o);return}switch(r){case"f32":this.typed=new bt(Float32Array,o);break;case"f64":this.typed=new bt(Float64Array,o);break;case"i32":this.typed=new bt(Int32Array,o);break;case"u32":this.typed=new bt(Uint32Array,o);break;case"u8":this.typed=new bt(Uint8Array,o);break;case"bool":this.bits=new xn(o);break;case"dict":{this.typed=new bt(Uint32Array,o),this.dictionary=e??Pa(t);break}case"string":case"list":case"json":this.values=[];break;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}this.validity=t.nullable?new xn(o):null}fillNumber(){const{meta:e}=this;if(e.dtype==="dict"){const t=this.dictionary,r=typeof e.fill=="string"?e.fill:"";if(this.validity===null)return t.intern(r);const o=t.codeOf(r);return o===x?0:o}return typeof e.fill=="number"?e.fill:0}fillValue(){if(this.inferrer===null)switch(this.meta.dtype){case"string":return typeof this.meta.fill=="string"?this.meta.fill:"";case"list":return Xy;default:return}}unsetEntry(){if(!this.meta.nullable)return this.meta.dtype==="json"?null:this.fillValue()}writeFill(e){const{components:t}=this.meta;if(this.typed!==null){const r=this.fillNumber();for(let o=0;o<t;o++)this.typed.set(e*t+o,r)}else this.bits!==null?this.bits.set(e,this.meta.fill===!0):this.values!==null&&(this.values[e]=this.fillValue())}storeRaw(e,t){this.checkRaw(e,t),this.values[e]=typeof t=="string"?Ro(t):t}checkRaw(e,t){const{meta:r}=this;typeof t=="string"?wr(t,{column:r.name,row:e}):typeof t=="object"&&cn(t,`${r.name}[${e}]`)}store(e,t){this.put(e,this.coerce(e,t))}coerce(e,t){const{meta:r}=this,{dtype:o,components:s}=r;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":{const i=typeof t=="boolean"?Number(t):t;if(typeof i=="number"){if(!yr(o,i))throw gn(r,e,`${i} is not representable`,i);return i}if(s===1||!Yu(i,s))throw gn(r,e,`not ${s} number(s)`,typeof i);for(let a=0;a<s;a++)if(!yr(o,i[a]))throw gn(r,e,`${i[a]} is not representable`,i[a]);return i}case"bool":return Br(t,"bool")===!0;case"dict":case"string":{const i=Br(t,"string");if(typeof i!="string")throw gn(r,e,"not a string",typeof t);return wr(i,{column:r.name,row:e}),Ro(i)}case"list":{if(!Array.isArray(t))throw gn(r,e,"not an array",typeof t);for(const i of t)Qy(r,e,i);return t.map(i=>typeof i=="string"?Ro(i):i)}case"json":return cn(t,`${r.name}[${e}]`),t;default:{const i=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${i}`,{dtype:i})}}}put(e,t){const{dtype:r,components:o}=this.meta;switch(r){case"f32":case"f64":case"i32":case"u32":case"u8":{const s=this.typed;if(typeof t=="number"){if(o===1)s.set(e,t);else for(let a=0;a<o;a++)s.set(e*o+a,t);return}const i=t;for(let a=0;a<o;a++)s.set(e*o+a,i[a]);return}case"bool":this.bits.set(e,t===!0);return;case"dict":this.typed.set(e,this.dictionary.intern(t));return;case"string":case"list":case"json":this.values[e]=t;return;default:{const s=r;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}}function sd(n,e){return n<e.length?e[n]:x}function Zy(n,e,t){let r=null;for(let o=0;o<t;o++)e[o]===x&&(r??=In(t,!0),Kt(r,o),n.nullCount++);if(r!==null){const{meta:o}=n;n.meta=ht(o.name,o.domain,{...Sn(o),nullable:!0}),n.validity=r}}function jr(n,e,t,r,o){return new Ws(ht(n,e,t),r,o)}class id{constructor(e,t){this.lists=e,this.alive=t,this.found=[],this.list=0,this.edge=e[0][0]}step(){for(;this.edge===x;){if(this.list++,this.list===this.lists.length)return!0;this.edge=this.lists[this.list][0]}const[,e,t,r]=this.lists[this.list];return this.alive.get(this.edge)&&t.get(this.edge)===r&&this.found.push(this.edge),this.edge=e.get(this.edge),!1}}class La{constructor(e){this.ids=null,this.idToIndex=null,this.weight=null,this.weightSet=null,this.weightMode="none",this.liveNodeCount=0,this.liveEdgeCount=0,this.selfLoopCount=0,this.nodeColumns=[],this.edgeColumns=[],this.extensions=[],this.options=e;const{resizable:t}=e,r=e.expectedNodes??0,o=e.expectedEdges??0;this.nodeAlive=new xn({capacity:r,resizable:t}),this.firstOut=new bt(Uint32Array,{capacity:r,resizable:t}),this.firstIn=new bt(Uint32Array,{capacity:r,resizable:t}),this.src=new bt(Uint32Array,{capacity:o,resizable:t}),this.dst=new bt(Uint32Array,{capacity:o,resizable:t}),this.edgeAlive=new xn({capacity:o,resizable:t}),this.nextOut=new bt(Uint32Array,{capacity:o,resizable:t}),this.nextIn=new bt(Uint32Array,{capacity:o,resizable:t}),e.weighted&&(this.weight=this.allocateWeights(o))}get nodeBound(){return this.nodeAlive.length}get edgeBound(){return this.edgeAlive.length}get hasTombstones(){return this.liveNodeCount<this.nodeBound||this.liveEdgeCount<this.edgeBound}reserve(e,t){e>0&&(this.firstOut.ensureCapacity(e),this.firstIn.ensureCapacity(e)),t>0&&(this.src.ensureCapacity(t),this.dst.ensureCapacity(t),this.nextOut.ensureCapacity(t),this.nextIn.ensureCapacity(t),this.weight!==null&&this.weight.ensureCapacity(t))}materialiseIds(){if(this.ids!==null&&this.idToIndex!==null)return;const e=this.nodeBound;$a(e);const t=new Array(e),r=new Map;for(let o=0;o<e;o++)t[o]=o,r.set(o,o);this.ids=t,this.idToIndex=r}pushNode(e){this.idToIndex!==null&&$a(this.idToIndex.size+1);const t=this.nodeAlive.push(!0);if(this.firstOut.push(x),this.firstIn.push(x),this.ids!==null&&this.idToIndex!==null){const r=e??t;this.ids.push(r),this.idToIndex.set(r,t)}return this.liveNodeCount++,t}pushAnonymousNodes(e){if(this.idToIndex!==null){for(let r=0;r<e;r++)this.pushNode(null);return}const t=this.nodeBound+e;this.nodeAlive.resize(t,!0),this.firstOut.resize(t,x),this.firstIn.resize(t,x),this.liveNodeCount+=e}ensureWeights(){return this.weight===null&&(this.weight=this.allocateWeights(this.edgeBound),this.weight.resize(this.edgeBound,1)),this.weight}trackWeight(e,t){if(this.weightSet!==null){e>=this.weightSet.length&&this.weightSet.resize(e+1,!1),this.weightSet.set(e,t);return}switch(this.weightMode){case"none":this.weightMode=t?"explicit":"omitted";return;case"explicit":t||this.allocateWeightSet(!0,e);return;case"omitted":t&&this.allocateWeightSet(!1,e);return;case"mixed":return;default:{const r=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${r}`,{mode:r})}}}weightExplicit(e){return this.weightSet===null?this.weightMode==="explicit":e<this.weightSet.length&&this.weightSet.get(e)}pushEdge(e,t,r){const o=this.src.push(e);return this.dst.push(t),r!==void 0?this.ensureWeights().push(r):this.weight!==null&&this.weight.push(1),this.trackWeight(o,r!==void 0),this.edgeAlive.push(!0),this.nextOut.push(this.firstOut.get(e)),this.firstOut.set(e,o),this.nextIn.push(this.firstIn.get(t)),this.firstIn.set(t,o),this.liveEdgeCount++,e===t&&this.selfLoopCount++,o}pushEdges(e,t,r){const o=e.length,s=this.edgeBound,i=s+o;return o===0||(this.src.pushAll(e),this.dst.pushAll(t),r!==null?this.ensureWeights().pushAll(r):this.weight!==null&&this.weight.resize(i,1),this.trackWeights(s,o,r!==null),this.edgeAlive.resize(i,!0),this.nextOut.resize(i),this.nextIn.resize(i),this.selfLoopCount+=tb(this.src.array,this.dst.array,s,i,{firstOut:this.firstOut.array,firstIn:this.firstIn.array,nextOut:this.nextOut.array,nextIn:this.nextIn.array}),this.liveEdgeCount+=o),s}trackWeights(e,t,r){const o=e+t;let s=this.weightSet;if(s===null)switch(this.weightMode){case"none":this.weightMode=r?"explicit":"omitted";return;case"explicit":if(r)return;s=this.allocateWeightSet(!0,e);break;case"omitted":if(!r)return;s=this.allocateWeightSet(!1,e);break;case"mixed":return;default:{const i=this.weightMode;throw new P("E_UNSUPPORTED",`unknown weight mode ${i}`,{mode:i})}}s.length<e&&s.resize(e,!1),s.resize(o,r)}killEdge(e){this.edgeAlive.set(e,!1),this.liveEdgeCount--,this.src.get(e)===this.dst.get(e)&&this.selfLoopCount--}outEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}inEdges(e){const t=[];for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&t.push(r);return Uint32Array.from(t).sort()}incidentEdges(e){const t=[];for(let r=this.firstOut.get(e);r!==x;r=this.nextOut.get(r))this.edgeAlive.get(r)&&t.push(r);for(let r=this.firstIn.get(e);r!==x;r=this.nextIn.get(r))this.edgeAlive.get(r)&&this.src.get(r)!==e&&t.push(r);return Uint32Array.from(t).sort()}edgesBetween(e,t,r){const o=(u,d)=>[this.firstOut.get(u),this.nextOut,this.dst,d],s=(u,d)=>[this.firstIn.get(u),this.nextIn,this.src,d],i=r||e===t?[o(e,t)]:[o(e,t),s(e,t)],a=r?[s(t,e)]:[o(t,e),s(t,e)],c=new id(i,this.edgeAlive),l=e===t?c:new id(a,this.edgeAlive);for(;;){if(c.step())return Uint32Array.from(c.found).sort();if(l.step())return Uint32Array.from(l.found).sort()}}byteLength(){let e=this.firstOut.array.byteLength+this.firstIn.array.byteLength+this.src.array.byteLength+this.dst.array.byteLength+this.nextOut.array.byteLength+this.nextIn.array.byteLength+Fe(this.nodeAlive.length)*4+Fe(this.edgeAlive.length)*4;this.weight!==null&&(e+=this.weight.array.byteLength),this.weightSet!==null&&(e+=Fe(this.weightSet.length)*4);for(const t of this.nodeColumns)e+=t.byteLength();for(const t of this.edgeColumns)e+=t.byteLength();for(const t of this.extensions)for(const r of t.columns)e+=r.byteLength();return e}allocateWeights(e){const{resizable:t}=this.options;return this.options.weightDtype==="f64"?new bt(Float64Array,{capacity:e,resizable:t}):new bt(Float32Array,{capacity:e,resizable:t})}allocateWeightSet(e,t){const r=new xn({capacity:t+1,resizable:this.options.resizable});return r.resize(t,e),r.push(!e),this.weightSet=r,this.weightMode="mixed",r}}function ad(n,e){const t=new Uint32Array(n);let r=0;for(let s=0;s<n;s++)(e[s>>>5]>>>(s&31)&1)===1?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<n;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function eb(n){const e=n.length,t=new Uint32Array(e);let r=0;for(let s=0;s<e;s++)n[s]===s?t[s]=r++:t[s]=x;const o=new Uint32Array(r);for(let s=0;s<e;s++){const i=t[s];i!==x&&(o[i]=s)}return{remap:t,origin:o,count:r}}function tb(n,e,t,r,o){const{firstOut:s,firstIn:i,nextOut:a,nextIn:c}=o;let l=0;for(let u=t;u<r;u++){const d=n[u],f=e[u];a[u]=s[d],s[d]=u,c[u]=i[f],i[f]=u,d===f&&l++}return l}function nb(n,e,t,r,o,s,i){const{firstOut:a,firstIn:c,nextOut:l,nextIn:u}=i,d=t.length;let f=0;for(let h=0;h<d;h++){const g=t[h],w=r[n[g]],p=r[e[g]];o[h]=w,s[h]=p,l[h]=a[w],a[w]=h,u[h]=c[p],c[p]=h,w===p&&f++}return f}function rb(n,e,t){const r=e.length;for(let o=0;o<r;o++)t[o]=n[e[o]]}function ob(n,e,t,r){for(let o=0;o<r;o++)Le(e,o)&&(t[o]=n[o])}function cd(n,e){const{nodes:t,edges:r}=e,o=new La({...n.options,weighted:n.weight!==null||e.mergedWeights!==null,expectedNodes:t.count,expectedEdges:r.count});if(o.nodeAlive.resize(t.count,!0),o.firstOut.resize(t.count,x),o.firstIn.resize(t.count,x),o.liveNodeCount=t.count,n.ids!==null){const l=new Array(t.count),u=new Map;for(let d=0;d<t.count;d++){const f=n.ids[t.origin[d]];l[d]=f,u.set(f,d)}o.ids=l,o.idToIndex=u}const{remap:s}=t,i=r.count,{origin:a}=r;if(o.weightMode=n.weightMode,(n.weightSet!==null||e.mergedWeightSet!==null)&&(o.weightSet=new xn({capacity:i,resizable:n.options.resizable}),o.weightMode="mixed"),o.src.resize(i),o.dst.resize(i),o.nextOut.resize(i),o.nextIn.resize(i),o.edgeAlive.resize(i,!0),o.liveEdgeCount=i,o.selfLoopCount=nb(n.src.array,n.dst.array,a,s,o.src.array,o.dst.array,{firstOut:o.firstOut.array,firstIn:o.firstIn.array,nextOut:o.nextOut.array,nextIn:o.nextIn.array}),o.weight!==null){o.weight.resize(i);const l=o.weight.array;n.weight===null?l.fill(1,0,i):rb(n.weight.array,a,l),e.mergedWeights!==null&&e.mergedWeightStored!==null&&ob(e.mergedWeights,e.mergedWeightStored,l,i)}if(o.weightSet!==null){o.weightSet.resize(i,!1);for(let l=0;l<i;l++){let u=n.weightExplicit(a[l]);e.mergedWeightSet!==null&&Le(e.mergedWeightSet,l)&&(u=!0),u&&o.weightSet.set(l,!0)}}const c={node:s,edge:e.edgeValues??r.remap};return o.nodeColumns=n.nodeColumns.map(l=>l.gather(t.origin,Ma(l,c))),o.edgeColumns=n.edgeColumns.map(l=>l.gather(r.origin,Ma(l,c))),o.extensions=n.extensions.map(l=>({name:l.name,rowCount:l.rowCount,columns:l.columns.map(u=>u.gather(null,Ma(u,c)))})),o}function Ma(n,e){switch(n.meta.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ua(n){return n instanceof Uint32Array||n instanceof Int32Array||n instanceof Float32Array||n instanceof Float64Array||n instanceof Uint8Array}function sb(n){if(typeof n!="object"||n===null||Array.isArray(n)||Ua(n))return!1;const e=n;return typeof e.dtype=="string"&&typeof e.meta=="object"&&typeof e.length=="number"}function ib(n){return n.mutations}function Vs(n){n.sealed=!0}function ab(n){it(n);for(const e of Sa(n))it(e)}class wn{constructor(e){this.mutations=0,this.sealed=!1;const{domain:t,rowCount:r}=e;if(!(Number.isInteger(r)&&r>=0))throw new P("E_COLUMN_LENGTH",`invalid row count ${r} for a ${t} table`,{domain:t,found:r});this.domain=t,this.rowCount=r,this.columns=new Map;for(const o of e.columns){const{name:s}=o.meta;if(this.columns.has(s))throw new P("E_COLUMN_EXISTS",`column "${s}" is declared twice`,{column:s});this.checkColumn(s,o),this.checkRole(s,o.meta.role,!1),this.columns.set(s,o),ab(o)}}names(){return[...this.columns.keys()]}has(e){return this.columns.has(e)}get(e){return this.columns.get(e)??null}require(e){const t=this.columns.get(e);if(t===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${this.domain} column named "${e}"`,{column:e,domain:this.domain});return t}typed(e,t){const r=this.columns.get(e);return r?.dtype!==t?null:r}requireTyped(e,t){const r=this.require(e);if(r.dtype!==t)throw new P("E_COLUMN_TYPE",`column "${e}" is ${r.dtype}, expected ${t}`,{column:e,expected:t,found:r.dtype});return r}byRole(e){for(const t of this.columns.values())if(t.meta.role===e)return t;return null}value(e,t){return this.require(e).value(t)}isSet(e,t){return this.require(e).isSet(t)}set(e,t,r,o){this.assertWritable(e);const s=r??{};let i;if(Ua(t)){const c=zt("adopt",o?.adopt,["copy","strict"])??"copy";i=Ey(this.domain,this.rowCount,e,t,s,c)}else if(Array.isArray(t))i=xa(this.domain,this.rowCount,e,t,s);else if(sb(t)){if(!gy(t))throw new P("E_COLUMN_TYPE",`column "${e}": not a Column of this package`,{column:e,reason:"foreign column"});i=this.adoptColumn(e,t,r),i!==t&&N0(t)>0&&Gn(i)}else throw new P("E_COLUMN_TYPE",`column "${e}": unsupported data (${typeof t})`,{column:e,found:typeof t});this.checkRole(e,i.meta.role,o?.replaceRole??!1);const a=this.columns.get(e);if(a!==i&&(it(i),a!==t))for(const c of Sa(i))it(c);return this.columns.set(e,i),this.mutations++,i}remove(e){this.assertWritable(e);const t=this.columns.delete(e);return t&&this.mutations++,t}rename(e,t){this.assertWritable(e);const r=this.require(e);if(e===t)return;if(this.columns.has(t))throw new P("E_COLUMN_EXISTS",`cannot rename "${e}": a column named "${t}" exists`,{column:t});const o=Xu(r,ht(t,this.domain,Sn(r.meta)));it(o),Fr(r)&&Gn(o);const s=[...this.columns.entries()];this.columns.clear();for(const[i,a]of s)i===e?this.columns.set(t,o):this.columns.set(i,a);this.mutations++}gpuView(e){return py(this.require(e))}clone(){return new wn({domain:this.domain,rowCount:this.rowCount,columns:[...this.columns.values()]})}[Symbol.iterator](){return this.columns.values()}adoptColumn(e,t,r){this.checkColumn(e,t);const{meta:o}=t;if(r===void 0&&o.name===e&&o.domain===this.domain)return t;const i={...Sn(o),...r};return r?.fill===void 0&&(i.fill=o.fill),Xu(t,ht(e,this.domain,i))}assertWritable(e){if(this.sealed)throw new P("E_FROZEN",`the ${this.domain} table is sealed: its column set cannot change (column "${e}")`,{domain:this.domain,column:e})}checkColumn(e,t){if(t.length!==this.rowCount)throw new P("E_COLUMN_LENGTH",`column "${e}" has ${t.length} rows; the ${this.domain} table has ${this.rowCount}`,{column:e,expected:this.rowCount,found:t.length})}checkRole(e,t,r){if(t!==null){for(const[o,s]of this.columns)if(o!==e&&s.meta.role===t){if(!r)throw new P("E_DUPLICATE_ROLE",`role "${t}" is already held by column "${o}" in the ${this.domain} table`,{role:t,column:e,holder:o});this.columns.delete(o);return}}}}function ld(n,e){const t=n.clone();for(const r of Object.keys(e)){const o=e[r];Ua(o)?t.set(r,o):t.set(r,o.data,o.decl)}return t}function cb(n,e){const{dtype:t}=n;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":return n.meta.components===1?n.data[e]:Array.from(n.data.subarray(e*n.meta.components,(e+1)*n.meta.components)).join(",");case"bool":return Le(n.data,e);case"dict":return n.codes[e];case"string":return n.valueAt(e);case"list":return JSON.stringify(n.sliceOf(e));case"json":return JSON.stringify(n.values[e]);default:{const r=t;throw new P("E_COLUMN_TYPE",`unknown dtype ${r}`,{dtype:r})}}}function ud(n){if(!n.meta.unique)return;const e=new Map;for(let t=0;t<n.length;t++){if(!n.isSet(t))continue;const r=cb(n,t),o=e.get(r);if(o!==void 0){const s=n.meta.domain==="edge"?"E_DUPLICATE_EDGE_ID":"E_DUPLICATE_ID";throw new P(s,`column "${n.meta.name}" is unique but rows ${o} and ${t} hold the same value`,{column:n.meta.name,domain:n.meta.domain,rows:[o,t],value:n.value(t)})}e.set(r,t)}}function lb(n){for(const e of n)ud(e)}function js(n){return new P("E_COLUMN_TYPE",`column ${JSON.stringify(n.meta.name)} of dtype ${n.dtype} cannot hold edge ids`,{column:n.meta.name,dtype:n.dtype,reason:"edge id dtype"})}function ub(n,e){switch(n.dtype){case"string":return n.valueAt(e);case"dict":return n.dictionary[n.codes[e]];case"f32":case"f64":case"i32":case"u32":case"u8":return n.data[e*n.meta.components];case"bool":case"list":case"json":throw js(n);default:throw js(n)}}function dd(n){switch(n.dtype){case"string":case"dict":case"f32":case"f64":case"i32":case"u32":case"u8":return!0;case"bool":case"list":case"json":return!1;default:return!1}}function db(n){if(!dd(n))throw js(n);const e=new Map,t=n.length;for(let r=0;r<t;r++){if(!n.isSet(r))continue;const o=ub(n,r);e.has(o)||e.set(o,r)}return e}class fb{constructor(e){if(!dd(e))throw js(e);this.column=e,this.map=null,this.builtVersion=-1}get built(){return this.map!==null&&this.builtVersion===this.column.version}get size(){return this.ensure().size}indexOf(e){const t=this.ensure().get(e);return t===void 0?x:t}has(e){return this.ensure().has(e)}ensure(){const{version:e}=this.column;return(this.map===null||this.builtVersion!==e)&&(this.map=db(this.column),this.builtVersion=e),this.map}}const Ho=["rowPtr","colIdx","weights","arcToEdge","edgeToArc"];function hb(n){const e=n.identity?0:n.arcCount,t=n.identity?0:n.edgeCount;return[4*(n.nodeCount+1),4*n.arcCount,n.weighted?4*n.arcCount:0,4*e,4*t]}function gb(n){return{rowPtr:new Uint32Array(n.nodeCount+1),colIdx:new Uint32Array(n.arcCount),weights:n.weighted?new Float32Array(n.arcCount):null,arcToEdge:n.identity?null:new Uint32Array(n.arcCount),edgeToArc:n.identity?null:new Uint32Array(n.edgeCount),arena:null}}function fd(n){const e=hb(n),t=V0(e,ft),r=new ArrayBuffer(t.byteLength),o={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let s=0;for(let l=0;l<Ho.length;l++){const u=t.offsets[l];if(u===null)continue;const d=Object.freeze({byteOffset:u,byteLength:e[l]});o[Ho[l]]=d,l<=2&&(s=u+e[l])}const i=(l,u)=>{const d=o[l];return d===null?new Uint32Array(0):new Uint32Array(r,d.byteOffset,u)};let a=null;if(n.weighted){const l=o.weights;a=l===null?new Float32Array(0):new Float32Array(r,l.byteOffset,n.arcCount)}const c=Object.freeze({buffer:r,byteOffset:0,byteLength:t.byteLength,alignment:ft,segments:Object.freeze(o),hotByteLength:s});return{rowPtr:i("rowPtr",n.nodeCount+1),colIdx:i("colIdx",n.arcCount),weights:a,arcToEdge:n.identity?null:i("arcToEdge",n.arcCount),edgeToArc:n.identity?null:i("edgeToArc",n.edgeCount),arena:c}}function wb(n,e){return e?fd(n):gb(n)}function pb(n){return{nodeCount:n.rowPtr.length-1,arcCount:n.colIdx.length,edgeCount:n.edgeToArc===null?n.colIdx.length:n.edgeToArc.length,weighted:n.weights!==null,identity:n.arcToEdge===null}}function mb(n){const e=fd(pb(n));return e.rowPtr.set(n.rowPtr),e.colIdx.set(n.colIdx),e.weights!==null&&n.weights!==null&&e.weights.set(n.weights),e.arcToEdge!==null&&n.arcToEdge!==null&&e.arcToEdge.set(n.arcToEdge),e.edgeToArc!==null&&n.edgeToArc!==null&&e.edgeToArc.set(n.edgeToArc),e}function Fa(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<r?o=i+1:s=i}return o}function hd(n,e,t,r){let o=e,s=t;for(;o<s;){const i=o+Math.floor((s-o)/2);n[i]<=r?o=i+1:s=i}return o}function yb(n,e,t,r){const o=n[t+1],s=Fa(e,n[t],o,r);return s<o&&e[s]===r?s:x}function qs(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r),a=hd(e,i,s,r);return[i,a]}function gd(n,e,t,r){const o=n[t],s=n[t+1],i=Fa(e,o,s,r);return hd(e,i,s,r)-i}function bb(n,e){let t=0,r=n.length;for(;t<r;){const o=t+Math.floor((r-t)/2);n[o]<=e?t=o+1:r=o}return t-1}function vb(n,e,t){return gd(n,e,t,t)}const wd=1024,pd=32,Ab=1;function Ba(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return e}class Ko{constructor(e,t,r,o,s){this.source=e,this.directed=e.directed,this.nodeCount=e.nodeCount,this.arcCount=e.arcCount,this.rowPtr=t,this.colIdx=r,this.weights=o,this.fwdArcCache=s,this.fwdArcIsIdentity=s===null,this.arcToEdgeCache=null,this.arcToEdgeOwned=!1}get fwdArc(){return this.fwdArcCache??=Ba(this.arcCount),this.fwdArcCache}get arcToEdge(){if(this.arcToEdgeCache===null)if(this.fwdArcIsIdentity)this.arcToEdgeCache=this.source.arcToEdge;else if(this.source.flags.arcToEdgeIsIdentity)this.arcToEdgeCache=this.fwdArc;else{const{fwdArc:e}=this,t=this.source.arcToEdge,r=new Uint32Array(this.arcCount);for(let o=0;o<r.length;o++)r[o]=t[e[o]];this.arcToEdgeCache=r,this.arcToEdgeOwned=!0}return this.arcToEdgeCache}get ownedByteLength(){let e=0;return this.directed&&(e+=this.rowPtr.byteLength+this.colIdx.byteLength,this.weights!==null&&(e+=this.weights.byteLength)),this.fwdArcCache!==null&&(e+=this.fwdArcCache.byteLength),this.arcToEdgeOwned&&this.arcToEdgeCache!==null&&(e+=this.arcToEdgeCache.byteLength),e}materialised(){const e={rowPtr:this.rowPtr,colIdx:this.colIdx};return this.weights!==null&&(e.weights=this.weights),this.fwdArcCache!==null&&(e.fwdArc=this.fwdArcCache),this.arcToEdgeCache!==null&&(e.arcToEdge=this.arcToEdgeCache),e}}function Eb(n){const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o,weights:s}=n;if(!n.directed)return new Ko(n,r,o,s,null);const i=new Uint32Array(e+1);for(let d=0;d<t;d++)i[o[d]+1]++;for(let d=0;d<e;d++)i[d+1]+=i[d];const a=new Uint32Array(t),c=new Uint32Array(t),l=s===null?null:new Float32Array(t),u=i.slice(0,e);for(let d=0;d<e;d++){const f=r[d+1];for(let h=r[d];h<f;h++){const g=o[h],w=u[g]++;a[w]=d,c[w]=h,l!==null&&s!==null&&(l[w]=s[h])}}return new Ko(n,i,a,l,c)}function md(n,e,t){const r=new Uint32Array(t);for(let o=0;o<e;o++){const s=n[o+1];for(let i=n[o];i<s;i++)r[i]=o}return r}function _b(n){return yd(n,md(n.rowPtr,n.nodeCount,n.arcCount))}function yd(n,e){return Object.freeze({src:e,dst:n.colIdx,weights:n.weights,get arcToEdge(){return n.arcToEdge}})}function bd(n){const{nodeCount:e,edgeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;if(n.flags.arcToEdgeIsIdentity)return za(n,md(o,e,r),s,i);const{arcToEdge:a,edgeToArc:c}=n,l=new Uint32Array(t),u=new Uint32Array(t);for(let f=0;f<e;f++){const h=o[f+1];for(let g=o[f];g<h;g++){const w=a[g];c[w]===g&&(l[w]=f,u[w]=s[g])}}let d=null;if(i!==null){d=new Float32Array(t);for(let f=0;f<t;f++)d[f]=i[c[f]]}return za(n,l,u,d)}function za(n,e,t,r){return Object.freeze({src:e,dst:t,weights:r,get arc(){return n.edgeToArc}})}function Ar(n,e){const t=new Uint32Array(e);for(let r=0;r<e;r++)t[r]=n[r+1]-n[r];return t}function Ib(n,e){const t=new Uint32Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function vd(n,e,t){const r=new Float64Array(t);for(let o=0;o<t;o++){const s=n[o+1];let i=0;for(let a=n[o];a<s;a++)i+=e[a];r[o]=i}return r}function Ga(n){return new Float64Array(n)}function kb(n,e){const t=new Float64Array(n.length);for(let r=0;r<t.length;r++)t[r]=n[r]+e[r];return t}function Sb(n){const{weights:e,edgeCount:t}=n;if(e===null)return t;let r=0;if(n.flags.arcToEdgeIsIdentity){for(let s=0;s<e.length;s++)r+=e[s];return r}const{edgeToArc:o}=n;for(let s=0;s<t;s++)r+=e[o[s]];return r}function Pb(n){const{nodeCount:e,rowPtr:t,colIdx:r,selfLoopCount:o}=n,s=new Uint32Array(e),i=new Uint32Array(o);let a=0;for(let c=0;c<e;c++){const[l,u]=qs(t,r,c,c);s[c]=u-l;for(let d=l;d<u&&a<o;d++)i[a++]=d}return{selfLoopArcs:i,selfLoopsPerNode:s}}function xb(n,e){const{weights:t,nodeCount:r,rowPtr:o,colIdx:s}=n;if(t===null)return Ga(e.selfLoopsPerNode);const i=new Float64Array(r);for(let a=0;a<r;a++){if(e.selfLoopsPerNode[a]===0)continue;const[c,l]=qs(o,s,a,a);let u=0;for(let d=c;d<l;d++)u+=t[d];i[a]=u}return i}function Cb(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant I7 violated: arc ${t} in row ${n} targeting ${e} has no mate in row ${e}`,{invariant:"I7",row:n,arc:t,target:e})}function Nb(n){if(n.directed)throw new P("E_DIRECTED","mate() is defined for undirected snapshots only",{directed:!0});const{nodeCount:e,arcCount:t,rowPtr:r,colIdx:o}=n,s=new Uint32Array(t),i=r.slice(0,e);for(let a=0;a<e;a++){const c=r[a+1];let l=i[a];for(;l<c;){const u=o[l];let d=l+1;for(;d<c&&o[d]===u;)d++;const f=d-l;if(u===a)for(let h=0;h<f;h++)s[l+h]=l+h;else{const h=i[u];if(u<a||h+f>r[u+1]||o[h]!==a||o[h+f-1]!==a)throw Cb(a,u,l);for(let g=0;g<f;g++)s[l+g]=h+g,s[h+g]=l+g;i[u]=h+f}l=d}i[a]=c}return s}function Ad(n,e){const t=Ar(n,e);let r=0;for(let d=0;d<e;d++)t[d]>r&&(r=t[d]);const o=new Uint32Array(r+1);for(let d=0;d<e;d++)o[t[d]]++;let s=0;for(let d=r;d>=0;d--){const f=o[d];o[d]=s,s+=f}const i=new Uint32Array(e);let a=0,c=0,l=0;for(let d=0;d<e;d++){const f=t[d];i[o[f]++]=d,f>=wd?a++:f>=pd?c++:f>=Ab&&l++}const u=new Uint32Array([0,a,a+c,a+c+l,e]);return Object.freeze({perm:i,segmentOffsets:u})}function Tb(n,e){if(!n.directed)return!0;const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,weights:i}=n;for(let u=0;u<=t;u++)if(o[u]!==e.rowPtr[u])return!1;const a=e.colIdx;for(let u=0;u<r;u++)if(s[u]!==a[u])return!1;const c=e.weights;if(i===null||c===null)return!0;if(!n.flags.multigraph){for(let u=0;u<r;u++)if(i[u]!==c[u])return!1;return!0}let l=0;for(;l<r;){let u=l+1;for(;u<r&&s[u]===s[l]&&u<o[Ob(o,t,l)+1];)u++;if(u-l===1){if(i[l]!==c[l])return!1}else if(!$b(i,c,l,u))return!1;l=u}return!0}function Ob(n,e,t){let r=0,o=e;for(;o-r>1;){const s=r+o>>>1;n[s]<=t?r=s:o=s}return r}function $b(n,e,t,r){const o=n.slice(t,r).sort(),s=e.slice(t,r).sort();for(let i=0;i<o.length;i++)if(o[i]!==s[i]&&!(Number.isNaN(o[i])&&Number.isNaN(s[i])))return!1;return!0}function Rb(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.ownedByteLength:0;case"coo":return t.src.byteLength;case"edgeList":{const r=t;let o=r.src.byteLength;return r.dst!==n.colIdx&&(o+=r.dst.byteLength),r.weights!==null&&r.weights!==n.weights&&(o+=r.weights.byteLength),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return t.byteLength;case"degreeOrder":case"reverseDegreeOrder":{const r=t;return r.perm.byteLength+r.segmentOffsets.byteLength}case"totalWeight":case"symmetric":return 0;default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Wa(n,e,t){switch(e){case"reverse":return t instanceof Ko?t.materialised():{};case"coo":return{src:t.src};case"edgeList":{const r=t,o={src:r.src};return r.dst!==n.colIdx&&(o.dst=r.dst),r.weights!==null&&r.weights!==n.weights&&(o.weights=r.weights),o}case"outDegree":case"inDegree":case"degree":case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":case"selfLoopArcs":case"selfLoopsPerNode":case"mate":return{data:t};case"degreeOrder":case"reverseDegreeOrder":{const r=t;return{perm:r.perm,segmentOffsets:r.segmentOffsets}}case"totalWeight":case"symmetric":return{};default:{const r=e;throw new P("E_UNSUPPORTED",`unknown view ${String(r)}`,{view:r})}}}function Ed(n,e){return n instanceof Float64Array?new Float64Array(e):n instanceof Float32Array?new Float32Array(e):n instanceof Int32Array?new Int32Array(e):new Uint32Array(e)}function Db(n,e,t,r){const{edgeCount:o,arcCount:s}=n;if(zt("reducer",t,["first","sum","max","min"]),e.length!==s)throw new P("E_COLUMN_LENGTH",`perArc has ${e.length} entries, expected ${s}`,{expected:s,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const i=Ed(e,o),{edgeToArc:a,arcToEdge:c}=n;for(let l=0;l<o;l++)i[l]=e[a[l]];switch(t){case"first":break;case"sum":for(let l=0;l<s;l++){const u=c[l];a[u]!==l&&(i[u]+=e[l])}break;case"max":for(let l=0;l<s;l++){const u=c[l];e[l]>i[u]&&(i[u]=e[l])}break;case"min":for(let l=0;l<s;l++){const u=c[l];e[l]<i[u]&&(i[u]=e[l])}break;default:{const l=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(l)}`,{reducer:l})}}return i}function Va(n,e,t){const{edgeCount:r,arcCount:o}=n;if(e.length!==r)throw new P("E_COLUMN_LENGTH",`perEdge has ${e.length} entries, expected ${r}`,{expected:r,found:e.length});if(n.flags.arcToEdgeIsIdentity)return e;const s=t??Ed(e,o),{arcToEdge:i}=n;for(let a=0;a<o;a++)s[a]=e[i[a]];return s}function ie(n,e,t={}){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function Lb(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Mb(n,e,t){let r=0;for(let o=0;o<t;o++){const s=n[o+1];for(let i=n[o];i<s;i++)e[i]===o&&r++}return r}function qr(n){for(let e=0;e<n.length;e++)if(n[e]!==e)return!1;return!0}function _d(n){const{directed:e,nodeCount:t,rowPtr:r,colIdx:o,weights:s,arcToEdge:i}=n;let a=!0,c=!0,l=!0;if(s!==null)for(let u=0;u<s.length;u++){const d=s[u];d!==1&&(a=!1),d>=0||(c=!1),Number.isFinite(d)||(l=!1)}return{multigraph:Lb(r,o,t),hasSelfLoops:n.selfLoopCount>0,arcToEdgeIsIdentity:e&&(i===null||qr(i)),weighted:s!==null,allWeightsOne:a,nonNegativeWeights:c,finiteWeights:l}}function Ub(n){const{rowPtr:e,colIdx:t,nodeCount:r,arcCount:o}=n;if(e.length!==r+1)throw ie("I1",`rowPtr has ${e.length} entries, expected ${r+1}`,{expected:r+1,found:e.length});if(e[0]!==0)throw ie("I1",`rowPtr[0] is ${e[0]}, expected 0`,{row:0,found:e[0]});for(let s=0;s<r;s++)if(e[s+1]<e[s])throw ie("I1",`rowPtr decreases at row ${s}: ${e[s]} -> ${e[s+1]}`,{row:s});if(e[r]!==o||t.length!==o)throw ie("I1",`rowPtr[${r}] = ${e[r]}, colIdx.length = ${t.length}, arcCount = ${o}`,{row:r,found:e[r],expected:o,colIdxLength:t.length})}function Fb(n){const{colIdx:e,nodeCount:t}=n;for(let r=0;r<e.length;r++)if(e[r]>=t)throw ie("I2",`colIdx[${r}] = ${e[r]} is not below nodeCount ${t}`,{arc:r,found:e[r]})}function Bb(n){const e=[["nodeCount",n.nodeCount],["edgeCount",n.edgeCount],["arcCount",n.arcCount],["selfLoopCount",n.selfLoopCount]];for(const[t,r]of e)if(!Number.isInteger(r)||r<0||r>Te)throw ie("I3",`${t} = ${r} is not an integer in [0, MAX_COUNT]`,{count:t,found:r});if(n.edgeCount>n.arcCount)throw ie("I3",`edgeCount ${n.edgeCount} exceeds arcCount ${n.arcCount}`,{edgeCount:n.edgeCount,arcCount:n.arcCount});if(n.selfLoopCount>n.edgeCount)throw ie("I3",`selfLoopCount ${n.selfLoopCount} exceeds edgeCount ${n.edgeCount}`,{selfLoopCount:n.selfLoopCount,edgeCount:n.edgeCount})}function zb(n){const{rowPtr:e,colIdx:t,nodeCount:r}=n,s=n.flags.arcToEdgeIsIdentity?null:n.arcToEdge;for(let i=0;i<r;i++){const a=e[i+1];for(let c=e[i]+1;c<a;c++){if(t[c]<t[c-1])throw ie("I4",`row ${i} is not sorted at arc ${c}`,{row:i,arc:c});if(t[c]===t[c-1]&&s!==null&&s[c]<=s[c-1])throw ie("I4",`parallel arcs ${c-1} and ${c} in row ${i} are not in edge order`,{row:i,arc:c})}}}function Gb(n){const{arcCount:e,edgeCount:t}=n;if(n.flags.arcToEdgeIsIdentity){if(!n.directed||e!==t)throw ie("I5","identity permutation claimed on a snapshot where it cannot hold",{directed:n.directed,arcCount:e,edgeCount:t});return}const{arcToEdge:r,edgeToArc:o}=n;if(r.length!==e)throw ie("I5",`arcToEdge has ${r.length} entries, expected ${e}`,{expected:e,found:r.length});if(o.length!==t)throw ie("I5",`edgeToArc has ${o.length} entries, expected ${t}`,{expected:t,found:o.length});for(let s=0;s<e;s++)if(r[s]>=t)throw ie("I5",`arcToEdge[${s}] = ${r[s]} is not below edgeCount ${t}`,{arc:s,found:r[s]});for(let s=0;s<t;s++)if(o[s]>=e)throw ie("I5",`edgeToArc[${s}] = ${o[s]} is not below arcCount ${e}`,{edge:s,found:o[s]})}function Wb(n){if(n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:e,edgeToArc:t,edgeCount:r}=n;for(let o=0;o<r;o++)if(e[t[o]]!==o)throw ie("I5",`arcToEdge[edgeToArc[${o}]] = ${e[t[o]]}, expected ${o}`,{edge:o,arc:t[o]})}function Id(n,e){if(!n.directed)return;const{arcCount:t,edgeCount:r}=n;if(t!==r)throw ie("I6",`directed snapshot has arcCount ${t} but edgeCount ${r}`,{arcCount:t,edgeCount:r});if(!e||n.flags.arcToEdgeIsIdentity)return;const{arcToEdge:o}=n,s=new Uint8Array(r);for(let i=0;i<t;i++){const a=o[i];if(a>=r||s[a]===1)throw ie("I6",`edge ${a} appears more than once in arcToEdge (arc ${i})`,{arc:i,edge:a});s[a]=1}}function Vb(n){if(n.directed)return;const e=2*n.edgeCount-n.selfLoopCount;if(n.arcCount!==e)throw ie("I7",`undirected snapshot has arcCount ${n.arcCount}, expected 2 * ${n.edgeCount} - ${n.selfLoopCount} = ${e}`,{arcCount:n.arcCount,expected:e})}function jb(n){if(n.directed)return;const{nodeCount:e,arcCount:t,edgeCount:r,rowPtr:o,colIdx:s,weights:i,arcToEdge:a}=n,c=new Uint8Array(r);for(let u=0;u<t;u++){const d=a[u];if(c[d]===2)throw ie("I7",`edge ${d} appears more than twice in arcToEdge (arc ${u})`,{arc:u,edge:d});c[d]++}const l=o.slice(0,e);for(let u=0;u<e;u++){const d=o[u+1];let f=l[u];if(f<o[u]||f>d)throw ie("I7",`row ${u} was over-consumed by mates from earlier rows`,{row:u});for(;f<d;){const h=s[f];let g=f+1;for(;g<d&&s[g]===h;)g++;const w=g-f;if(h===u){for(let p=f;p<g;p++)if(c[a[p]]!==1)throw ie("I7",`self-loop edge ${a[p]} has more than one arc`,{row:u,arc:p,edge:a[p]})}else{if(h<u)throw ie("I7",`arc ${f} in row ${u} targets ${h} but row ${h} holds no mate`,{row:u,arc:f,target:h});const p=l[h],m=o[h+1];for(let y=0;y<w;y++){const b=f+y,v=p+y;if(v>=m||s[v]!==u)throw ie("I7",`arc ${b} in row ${u} targeting ${h} has no mate in row ${h}`,{row:u,arc:b,target:h});if(a[v]!==a[b])throw ie("I7",`arcs ${b} and ${v} should share a logical edge but hold ${a[b]} and ${a[v]}`,{row:u,arc:b,mate:v});if(c[a[b]]!==2)throw ie("I7",`edge ${a[b]} of arc ${b} does not have two arcs`,{row:u,arc:b,edge:a[b]});if(i!==null&&i[b]!==i[v])throw ie("I7",`arcs ${b} and ${v} carry different weights ${i[b]} and ${i[v]}`,{row:u,arc:b,mate:v})}if(p+w<m&&s[p+w]===u)throw ie("I7",`row ${h} holds more arcs to ${u} than row ${u} holds to ${h}`,{row:h,arc:p+w,target:u});l[h]=p+w}f=g}l[u]=d}}function qb(n){const{weights:e,arcCount:t}=n;if(e!==null&&e.length!==t)throw ie("I8",`weights has ${e.length} entries, expected ${t}`,{expected:t,found:e.length})}function Hb(n){const{weights:e}=n;if(e!==null){for(let t=0;t<e.length;t++)if(Number.isNaN(e[t]))throw ie("I8",`weights[${t}] is NaN`,{arc:t})}}function Kb(n){const e=Mb(n.rowPtr,n.colIdx,n.nodeCount);if(e!==n.selfLoopCount)throw ie("I9",`selfLoopCount is ${n.selfLoopCount} but ${e} loop arcs exist`,{reason:"selfLoopCount",expected:e,found:n.selfLoopCount});const t=_d({directed:n.directed,nodeCount:n.nodeCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:n.flags.arcToEdgeIsIdentity?null:n.arcToEdge,selfLoopCount:n.selfLoopCount}),r=["multigraph","hasSelfLoops","arcToEdgeIsIdentity","weighted","allWeightsOne","nonNegativeWeights","finiteWeights"];for(const o of r)if(n.flags[o]!==t[o])throw ie("I9",`flag ${o} is ${n.flags[o]} but the arrays say ${t[o]}`,{flag:o,found:n.flags[o],expected:t[o]})}function Yb(n,e,t){const r=n.segments[e];if(r===null)return;if(t===null)throw ie("I10",`arena names a segment for absent core array ${e}`,{array:e});const o=r.byteOffset-n.byteOffset;if(o<0||o%ft!==0||o+r.byteLength>n.byteLength)throw ie("I10",`arena segment ${e} at ${r.byteOffset} is not 256-aligned inside the arena`,{array:e,byteOffset:r.byteOffset});if(t.buffer!==n.buffer||t.byteOffset!==r.byteOffset||t.byteLength!==r.byteLength)throw ie("I10",`core array ${e} is not the view its arena segment describes`,{array:e,byteOffset:t.byteOffset,byteLength:t.byteLength})}function Xb(n,e){if(!j0(e))throw ie("I10",`core array ${n} is not 4-byte aligned`,{array:n,byteOffset:e.byteOffset,byteLength:e.byteLength});if(!pa(e))throw ie("I10",`core array ${n} is not a view over a plain ArrayBuffer`,{array:n,reason:"buffer"})}function Qb(n){const e=n.flags.arcToEdgeIsIdentity,t=[["rowPtr",n.rowPtr],["colIdx",n.colIdx],["weights",n.weights],["arcToEdge",e?null:n.arcToEdge],["edgeToArc",e?null:n.edgeToArc]];for(const[i,a]of t)a!==null&&Xb(i,a);const{arena:r}=n;if(r===null)return;const{alignment:o}=r;if(o!==ft)throw ie("I10",`arena alignment is ${o}, expected ${ft}`,{found:o});for(const[i,a]of t)Yb(r,i,a);let s=0;for(const i of["rowPtr","colIdx","weights"]){const a=r.segments[i];a!==null&&(s=a.byteOffset+a.byteLength-r.byteOffset)}if(r.hotByteLength!==s)throw ie("I10",`arena.hotByteLength is ${r.hotByteLength}, expected ${s}`,{reason:"hotByteLength",found:r.hotByteLength,expected:s})}function Jb(n){if(n.ids.size!==n.nodeCount)throw ie("I11",`ids.size is ${n.ids.size}, expected nodeCount ${n.nodeCount}`,{expected:n.nodeCount,found:n.ids.size})}function Zb(n){const{ids:e,nodeCount:t}=n;for(let r=0;r<t;r++){const o=e.idOf(r);if(typeof o=="number"&&Number.isNaN(o))throw ie("I11",`id of node ${r} is NaN`,{index:r});const s=e.indexOf(o);if(s!==r)throw ie("I11",`ids.indexOf(ids.idOf(${r})) is ${s}`,{index:r,found:s})}}function Ke(n,e,t,r={}){return ie("I12",`column "${e.meta.name}" of table ${n}: ${t}`,{table:n,column:e.meta.name,...r})}function kd(n,e,t,r,o){if(t.length!==r+1)throw Ke(n,e,`offsets has ${t.length} entries, expected ${r+1}`,{expected:r+1,found:t.length});if(t[0]!==0)throw Ke(n,e,`offsets[0] is ${t[0]}`,{row:0});for(let s=0;s<r;s++)if(t[s+1]<t[s])throw Ke(n,e,`offsets decrease at row ${s}`,{row:s});if(t[r]!==o)throw Ke(n,e,`offsets[${r}] is ${t[r]}, expected ${o}`,{row:r,found:t[r],expected:o})}function Sd(n,e,t,r,o,s){for(let i=0;i<t.length;i++){const a=t[i];if(a===x){const c=Math.floor(i/r);if(s!==void 0&&(s===null||Le(s,c)))throw Ke(n,e,`row ${c} is set but holds INVALID_INDEX`,{row:c});continue}if(a>=o)throw Ke(n,e,`value ${a} at ${i} is not below ${o}`,{row:Math.floor(i/r),found:a,expected:o})}}function Pd(n,e,t){switch(e.dtype){case"u32":Sd(n,e,e.data,e.meta.components,t,e.validity);return;case"list":{const{child:r}=e;if(r.dtype!=="u32")throw Ke(n,e,`refersTo list requires a u32 child, found ${r.dtype}`);Sd(n,e,r.data,1,t,void 0);return}default:throw Ke(n,e,`refersTo requires dtype u32, found ${e.dtype}`)}}function xd(n){switch(n.dtype){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":return[["data",n.data],["validity",n.validity]];case"dict":return[["codes",n.codes],["validity",n.validity]];case"string":return[["offsets",n.offsets],["utf8",n.utf8],["validity",n.validity]];case"list":return[["offsets",n.offsets],["validity",n.validity],...xd(n.child).map(([e,t])=>[`child.${e}`,t])];case"json":return[["validity",n.validity]];default:throw ie("I12",`unknown dtype ${n.dtype}`)}}function e1(n,e,t,r){if(e.length!==t)throw Ke(n,e,`has ${e.length} rows, expected ${t}`,{expected:t,found:e.length});const{validity:o,meta:s}=e,i=Math.ceil(t/32);if(o!==null&&o.length!==i)throw Ke(n,e,`validity has ${o.length} words, expected ${i}`,{expected:i,found:o.length});const a=o===null?0:t-gr(o,t);if(e.nullCount!==a)throw Ke(n,e,`nullCount is ${e.nullCount}, the validity bitmap says ${a}`,{expected:a,found:e.nullCount,reason:"nullCount"});for(const[u,d]of xd(e))if(d!==null&&!pa(d))throw Ke(n,e,`${u} is not a view over a plain ArrayBuffer`,{array:u,reason:"buffer"});const c=s.refersTo==="node"?r.nodeCount:r.edgeCount,{dtype:l}=e;switch(l){case"f32":case"f64":case"i32":case"u32":case"u8":{const u=t*s.components;if(e.data.length!==u)throw Ke(n,e,`data has ${e.data.length} values, expected ${u}`,{expected:u,found:e.data.length});s.refersTo!==null&&Pd(n,e,c);break}case"bool":if(e.data.length!==i)throw Ke(n,e,`bool data has ${e.data.length} words, expected ${i}`,{expected:i,found:e.data.length});break;case"dict":{if(e.codes.length!==t)throw Ke(n,e,`codes has ${e.codes.length} entries, expected ${t}`,{expected:t,found:e.codes.length});const u=e.dictionary.length;for(let d=0;d<t;d++)if(e.codes[d]>=u&&(o===null||Le(o,d)))throw Ke(n,e,`code ${e.codes[d]} at row ${d} is not below ${u}`,{row:d,found:e.codes[d]});break}case"string":kd(n,e,e.offsets,t,e.utf8.length);break;case"list":{const{child:u}=e;if(kd(n,e,e.offsets,t,u.length),u.validity!==null)throw Ke(n,e,"list child column has a validity bitmap");s.refersTo!==null&&Pd(n,e,c);break}case"json":if(e.values.length!==t)throw Ke(n,e,`values has ${e.values.length} entries, expected ${t}`,{expected:t,found:e.values.length});break;default:throw Ke(n,e,`unknown dtype ${String(l)}`)}}function Cd(n,e,t,r){for(const o of e)e1(n,o,t,r)}function t1(n){const e=[["nodes",n.nodes,n.nodeCount],["edges",n.edges,n.edgeCount],["graph",n.graph,1]];for(const[t,r,o]of e){if(r.rowCount!==o)throw ie("I12",`table ${t} has ${r.rowCount} rows, expected ${o}`,{table:t,expected:o,found:r.rowCount});Cd(t,r,o,n)}for(const[t,r]of n.extensions)Cd(`extensions[${t}]`,r,r.rowCount,n)}function n1(n){if(n.edges.rowCount!==n.edgeCount)throw ie("I13",`edge table has ${n.edges.rowCount} rows, expected edgeCount ${n.edgeCount}`,{expected:n.edgeCount,found:n.edges.rowCount})}function Nd(n){Bb(n),Ub(n),Fb(n),Gb(n),Id(n,!1),Vb(n),qb(n),Qb(n),Jb(n),n1(n),t1(n)}function r1(n){Nd(n),zb(n),Wb(n),Id(n,!0),Hb(n),jb(n),Kb(n),Zb(n);const e=[["nodes",n.nodes],["edges",n.edges],["graph",n.graph],...[...n.extensions].map(([t,r])=>[`extensions[${t}]`,r])];for(const[t,r]of e)for(const o of r)o1(t,o)}function o1(n,e){try{ud(e)}catch(t){throw t instanceof P&&(t.code==="E_DUPLICATE_ID"||t.code==="E_DUPLICATE_EDGE_ID")?Ke(n,e,t.message,{...t.details,reason:"unique",cause:t.code}):t}}class s1{constructor(e){const{nodeCount:t,arcCount:r,rowPtr:o,colIdx:s,directed:i}=e,a=new Uint32Array(r),c=new Uint32Array(t),l=i?new Uint32Array(t):Ar(o,t);for(let u=0;u<t;u++){const d=o[u+1];for(let f=o[u];f<d;f++){a[f]=u;const h=s[f];h===u&&c[u]++,i&&l[h]++}}this.arcRow=a,this.loops=c,this.inDegree=l}inDegreePrefix(){const e=this.inDegree.length,t=new Uint32Array(e+1);for(let r=0;r<e;r++)t[r+1]=t[r]+this.inDegree[r];return t}}function Ot(n,e,t,r){return ie(r,`carried view ${n}.${e} disagrees with the core at ${t}`,{view:n,member:e,index:t,reason:"view"})}function Er(n,e,t,r,o){for(let s=0;s<r.length;s++)if(!Object.is(t[s],r[s])&&t[s]!==r[s])throw Ot(n,e,s,o)}function Td(n,e,t){const r=new Uint8Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s>=t.length||r[s]===1)throw Ot(n,e,o,"I2");r[s]=1}}function i1(n,e){Er("outDegree","data",e,Ar(n.rowPtr,n.nodeCount),"I2")}function a1(n,e){Er("inDegree","data",e,n.inDegree,"I2")}function c1(n,e,t){const r=Ar(n.rowPtr,n.nodeCount),o=n.directed?e.inDegree:e.loops;for(let s=0;s<r.length;s++)if(t[s]!==r[s]+o[s])throw Ot("degree","data",s,"I2")}function l1(n,e){Er("selfLoopsPerNode","data",e,n.loops,"I2")}function u1(n,e,t){const{colIdx:r,arcCount:o}=n;for(let s=0;s<t.length;s++){const i=t[s];if(i>=o||r[i]!==e.arcRow[i]||s>0&&i<=t[s-1])throw Ot("selfLoopArcs","data",s,"I2")}}function d1(n,e){Er("coo","src",e,n.arcRow,"I2")}function f1(n,e,t,r,o){const{edgeCount:s,edgeToArc:i,colIdx:a,arcCount:c}=n,l=n.weights;for(let u=0;u<s;u++){const d=i[u];if(d>=c||t[u]!==e.arcRow[d])throw Ot("edgeList","src",u,"I2");if(r!==null&&r[u]!==a[d])throw Ot("edgeList","dst",u,"I2");if(o!==null&&l!==null&&!Object.is(o[u],l[d]))throw Ot("edgeList","weights",u,"I17")}}function h1(n,e,t){const{arcCount:r,arcToEdge:o,colIdx:s}=n;for(let i=0;i<r;i++){const a=t[i],c=s[i]===e.arcRow[i];if(a>=r||t[a]!==i||o[a]!==o[i]||a===i!==c)throw Ot("mate","data",i,"I2")}}function g1(n,e,t,r){Td(n,"perm",t);let o=0,s=0,i=0;for(let c=0;c<t.length;c++){const l=e[t[c]];if(c>0){const u=e[t[c-1]];if(l>u||l===u&&t[c]<t[c-1])throw Ot(n,"perm",c,"I2")}l>=wd?o++:l>=pd?s++:l>=1&&i++}const a=[0,o,o+s,o+s+i,t.length];Er(n,"segmentOffsets",r,a,"I2")}function w1(n,e,t,r,o){const s=n[t-1],i=e[s];if(o<i||o===i&&r<=s)throw Ot("reverse","fwdArc",t,"I2")}function p1(n,e,t){const{nodeCount:r,arcCount:o,colIdx:s}=n,i=n.weights,{rowPtr:a,fwdArc:c}=t,l=t.colIdx,u=t.weights;if(a[0]!==0||a[r]!==o)throw Ot("reverse","rowPtr",0,"I2");Er("reverse","rowPtr",a,e.inDegreePrefix(),"I2"),Td("reverse","fwdArc",c);for(let d=0;d<r;d++){const f=a[d+1];for(let h=a[d];h<f;h++){const g=c[h],w=e.arcRow[g];if(s[g]!==d||l[h]!==w)throw Ot("reverse","colIdx",h,"I2");if(h>a[d]&&w1(c,e.arcRow,h,g,w),u!==null&&i!==null&&!Object.is(u[h],i[g]))throw Ot("reverse","weights",h,"I17")}}}function m1(n,e,t){Er(n,"data",e,t,"I17")}const y1="@graphty/graph-format@4e2e91d4b533",b1=new Set(["totalWeight","symmetric"]),v1=new TextEncoder;function A1(n=Eu){if(!n)throw new P("E_UNSUPPORTED","the wire format cannot be written on a big-endian host",{reason:"big-endian host"})}const Yo="$num",Od="$esc";function E1(n){return Number.isNaN(n)?{[Yo]:"NaN"}:n===1/0?{[Yo]:"Infinity"}:n===-1/0?{[Yo]:"-Infinity"}:Object.is(n,-0)?{[Yo]:"-0"}:n}function qn(n){if(typeof n=="number")return E1(n);if(Array.isArray(n))return n.map(e=>qn(e));if(kn(n)){const e=Object.keys(n),t={};for(const r of e)$d(t,r,qn(n[r]));return e.length===1&&(e[0]===Yo||e[0]===Od)?{[Od]:t}:t}return n}function $d(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}class ja{constructor(e,t=!1){this.buffers=[],this.copied=[],this.segments=[],this.bufferIndex=new Map,this.placed=new Map,this.cursor=0,this.mode=e,this.transfer=t}get regionLength(){return hr(this.cursor,ft)}indexOf(e){return this.bufferIndex.get(e)??null}ref(e,t,r=!1){if(r&&Gn(e.buffer),this.mode==="reference")return{buffer:this.bufferIndexOf(e.buffer),byteOffset:e.byteOffset,byteLength:e.byteLength,dtype:t,length:e.length};const o=`${this.bufferIndexOf(e.buffer)}:${e.byteOffset}:${e.byteLength}:${t}`,s=this.placed.get(o);if(s!==void 0)return s;const i=hr(this.cursor,ft);this.cursor=i+e.byteLength;const a={buffer:0,byteOffset:i,byteLength:e.byteLength,dtype:t,length:e.length};return this.placed.set(o,a),this.segments.push({view:e,ref:a}),a}finalise(){if(!(this.mode!=="reference"||!this.transfer))for(let e=0;e<this.buffers.length;e++){const t=this.buffers[e];Fr(t)&&(this.buffers[e]=t.slice(0),this.copied.push(e))}}bufferIndexOf(e){const t=this.bufferIndex.get(e);if(t!==void 0)return t;const r=this.buffers.length;return this.bufferIndex.set(e,r),this.buffers.push(e),r}}function qa(n){return n instanceof Uint32Array?"u32":n instanceof Int32Array?"i32":n instanceof Float32Array?"f32":n instanceof Float64Array?"f64":"u8"}const Rd=new WeakMap,Dd=new WeakMap;function Ld(n,e){return n.offsets.length===e+1}function _1(n){const e=Rd.get(n);if(e!==void 0&&Ld(e,n.length))return e;const t=Do(n,n.length);return Rd.set(n,t),t}function I1(n){const e=Dd.get(n);if(e?.version===n.version&&Ld(e.encoded,n.length))return e.encoded;const t=new Array(n.length);for(let o=0;o<n.length;o++){const s=n.values[o];t[o]=s===void 0||!n.isSet(o)?"":JSON.stringify(qn(s))}const r=Do(t,t.length);return Dd.set(n,{version:n.version,encoded:r}),r}function Md(n,e,t){return{offsets:n.ref(e.offsets,"u32",t),utf8:n.ref(e.utf8,"utf8",t)}}function k1(n){return{name:n.name,domain:n.domain,dtype:n.dtype,components:n.components,itemDtype:n.itemDtype,itemComponents:n.itemComponents,nullable:n.nullable,mutable:n.mutable,role:n.role,refersTo:n.refersTo,unique:n.unique,default:qn(n.default),fill:qn(n.fill),options:n.options===null?null:qn(n.options),origin:n.origin===null?null:{...n.origin},dynamic:n.dynamic,extra:qn(n.extra)}}function Ud(n,e,t){const r=t||Fr(e),o={meta:k1(e.meta),data:null,validity:e.validity===null?null:n.ref(e.validity,"u32",r),nullCount:e.nullCount,dictionary:null,strings:null,offsets:null,child:null,jsonText:null},{dtype:s}=e;switch(s){case"f32":case"f64":case"i32":case"u32":case"u8":o.data=n.ref(e.data,s,r);break;case"bool":o.data=n.ref(e.data,"u32",r);break;case"dict":o.data=n.ref(e.codes,"u32",r),o.dictionary=Md(n,_1(e.dictionary),r);break;case"string":o.strings={offsets:n.ref(e.offsets,"u32",r),utf8:n.ref(e.utf8,"utf8",r)};break;case"list":o.offsets=n.ref(e.offsets,"u32",r),o.child=Ud(n,e.child,r);break;case"json":o.jsonText=Md(n,I1(e),r);break;default:{const i=s;throw new P("E_UNSUPPORTED",`unknown dtype ${i}`,{dtype:i})}}return o}function Hs(n,e){const t=[],r=Fr(e);for(const o of e)t.push(Ud(n,o,r));return t}function S1(n,e){const{ids:t}=e;if(!(t instanceof Yt))throw new P("E_UNSUPPORTED","the snapshot's id map is not a NodeIdMap of this package",{reason:"foreign id map"});const r=zy(t),o=Fr(t);return{kind:r.kind,size:r.size,offset:r.offset,values:r.values===null?null:n.ref(r.values,qa(r.values),o),tags:r.tags===null?null:n.ref(r.tags,"u8",o),numbers:r.numbers===null?null:n.ref(r.numbers,"f64",o),offsets:r.offsets===null?null:n.ref(r.offsets,"u32",o),utf8:r.utf8===null?null:n.ref(r.utf8,"utf8",o)}}function P1(n){return{name:n.name,description:n.description,creator:n.creator,created:n.created,modified:n.modified,keywords:[...n.keywords],sourceFormat:n.sourceFormat,sourceVersion:n.sourceVersion,idType:n.idType,timeFormat:n.timeFormat,timeRepresentation:n.timeRepresentation,mode:n.mode,declaredMultigraph:n.declaredMultigraph,weightOrigin:n.weightOrigin===null?null:{...n.weightOrigin},extra:qn(n.extra)}}function x1(n,e,t){if(t===void 0||t.length===0)return null;const r={};let o=0;for(const s of new Set(t)){if(b1.has(s))continue;const i=_v(e,s);if(i===null)continue;const a={};let c=!1;for(const[l,u]of Object.entries(Wa(e,s,i))){const d=u;a[l]=n.ref(d,qa(d)),c=!0}c&&(r[s]=a,o++)}return o===0?null:r}function Ha(n,e,t,r=!0){A1();const o=n.flags.arcToEdgeIsIdentity,s={rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:o?null:n.arcToEdge,edgeToArc:o?null:n.edgeToArc},i={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null},a=e.ref(n.rowPtr,"u32");i.rowPtr=a;for(const p of Ho){const m=s[p];p!=="rowPtr"&&m!==null&&m.length>0&&(i[p]=e.ref(m,qa(m)))}const c=C1(n,e,i),l=S1(e,n),u=r?Hs(e,n.nodes):[],d=r?Hs(e,n.edges):[],f=r?Hs(e,n.graph):[],h=[];if(r)for(const[p,m]of n.extensions)h.push({name:p,rowCount:m.rowCount,columns:Hs(e,m)});const g=x1(e,n,t);return e.finalise(),{manifest:{format:la,wire:[zn,_u],producer:y1,formatVersion:Mr,directed:n.directed,counts:{nodes:n.nodeCount,edges:n.edgeCount,arcs:n.arcCount,selfLoops:n.selfLoopCount},flags:{...n.flags},core:{rowPtr:a,colIdx:i.colIdx,weights:i.weights,arcToEdge:i.arcToEdge,edgeToArc:i.edgeToArc},arena:c,ids:l,nodeColumns:u,edgeColumns:d,graphColumns:f,extensions:h,meta:P1(n.meta),views:g,copied:e.copied,label:n.label},layout:e}}function C1(n,e,t){if(e.mode==="container"){let s=0,i=0;for(const a of Ho){const c=t[a];c!==null&&(s=c.byteOffset+c.byteLength,(a==="rowPtr"||a==="colIdx"||a==="weights")&&(i=s))}return{buffer:0,byteOffset:0,byteLength:s,hotByteLength:i}}const{arena:r}=n;if(r===null)return null;const o=e.indexOf(r.buffer);return o===null?null:{buffer:o,byteOffset:r.byteOffset,byteLength:r.byteLength,hotByteLength:r.hotByteLength}}function N1(n,e={}){const t=e.transfer===!0,r=new ja("reference",t),{manifest:o}=Ha(n,r,e.includeViews,e.includeColumns!==!1);return t&&Fd.set(n,[...r.buffers]),{manifest:o,buffers:r.buffers}}const Fd=new WeakMap;function T1(n){const e=Fd.get(n);if(e!==void 0)return[...e];const t=new ja("reference",!1);return Ha(n,t,void 0,!0),t.buffers.filter(r=>!Fr(r))}function O1(n){return v1.encode(JSON.stringify(n))}const $1=new Set(["u32","i32","f32","f64","u8","utf8"]),R1=new Set(["f32","f64","i32","u32","u8","bool","dict","string","list","json"]),D1=new Set(["identity","dense","numeric","string","mixed"]),L1=new Set(["string","integer","mixed"]),M1=new Set(["integer","double","date","dateTime"]),U1=new Set(["interval","timestamp"]),F1=new Set(["static","dynamic","slice"]),Bd=new Set(["__proto__","constructor","prototype"]),zd="$num",Gd="$esc",Wd=256;function Hr(n){return typeof n=="string"?JSON.stringify(n.length>40?`${n.slice(0,37)}...`:n):typeof n=="number"||typeof n=="boolean"||n===null?String(n):n===void 0?"undefined":`a ${typeof n}`}const B1="graphty.skippedColumns";function re(n,e,t={}){return new P("E_BAD_SERIALIZATION",`${n}: ${e}`,{ref:n,reason:e,...t})}function vt(n,e){if(!kn(n))throw re(e,"expected an object");return n}function Ks(n,e){if(!Array.isArray(n))throw re(e,"expected an array");return n}function Xo(n,e){if(typeof n!="string")throw re(e,"expected a string");return n}function Cn(n,e){return n==null?null:Xo(n,e)}function _r(n,e){if(typeof n!="boolean")throw re(e,"expected a boolean");return n}function z1(n,e){return n==null?null:_r(n,e)}function Nn(n,e){if(typeof n!="number"||!Number.isInteger(n)||n<0||n>Te)throw re(e,`expected an integer in [0, ${Te}]`,{found:n});return n===0?0:n}function Ys(n,e,t){if(n==null)return null;if(typeof n!="string"||!t.has(n))throw re(e,`unexpected value ${Hr(n)}`,{found:n});return n}function Vd(n){return typeof n=="string"&&R1.has(n)}function Hn(n,e,t=0){if(t>Wd)throw re(e,`JSON nesting deeper than ${Wd}`,{reason:"nesting"});if(Array.isArray(n))return n.map((o,s)=>Hn(o,`${e}[${s}]`,t+1));if(!kn(n))return n;const r=Object.keys(n);if(r.length===1&&r[0]===zd){const o=n[zd];switch(o){case"NaN":return Number.NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;case"-0":return-0;default:throw re(e,`unknown number tag ${Hr(o)}`,{found:o})}}if(r.length===1&&r[0]===Gd){const o=n[Gd];if(!kn(o))throw re(e,"an escaped object must hold a plain object",{found:typeof o});return jd(o,e,t)}return jd(n,e,t)}function jd(n,e,t){const r={};for(const o of Object.keys(n)){if(Bd.has(o))throw re(e,`forbidden key "${o}"`,{key:o});$d(r,o,Hn(n[o],`${e}.${o}`,t+1))}return r}function G1(n){const e=[n];for(;e.length>0;){const t=e.pop();if(Array.isArray(t))for(const r of t)e.push(r);else if(typeof t=="object"&&t!==null)for(const r of Object.keys(t)){if(Bd.has(r))throw re("manifest",`forbidden key "${r}"`,{key:r});e.push(t[r])}}}function qd(n,e){let t;try{t=JSON.parse(n)}catch(r){throw re(e,`not valid JSON (${r instanceof Error?r.message:String(r)})`)}return G1(t),t}function W1(n,e){return{level:e,copy:!1,unknownColumns:"error"}}function Hd(n,e,t){return{byteLength:t,locate(r){return{buffer:n,byteOffset:e+r}},read(r,o){const s=new Uint8Array(new ArrayBuffer(Mo(o)),0,o);return s.set(new Uint8Array(n,e+r,o)),s}}}function V1(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function j1(n){switch(n){case"u32":case"i32":case"f32":return 4;case"f64":return 8;case"u8":case"utf8":return 1;default:{const e=n;throw re("dtype",`unknown wire dtype ${e}`,{dtype:e})}}}function Kd(n,e,t,r){switch(n){case"u32":return new Uint32Array(e,t,r);case"i32":return new Int32Array(e,t,r);case"f32":return new Float32Array(e,t,r);case"f64":return new Float64Array(e,t,r);case"u8":case"utf8":return new Uint8Array(e,t,r);default:{const o=n;throw re("dtype",`unknown wire dtype ${o}`,{dtype:o})}}}function Xs(n,e){const t=vt(n,e),{dtype:r}=t;if(typeof r!="string"||!$1.has(r))throw re(e,`unknown wire dtype ${Hr(r)}`,{found:r});const o=["buffer","byteOffset","byteLength","length"];for(const s of o){const i=t[s];if(typeof i!="number"||!Number.isInteger(i)||i<0)throw re(`${e}.${s}`,"expected a non-negative integer",{found:i})}return{buffer:t.buffer,byteOffset:t.byteOffset,byteLength:t.byteLength,dtype:r,length:t.length}}function Ka(n,e){return n instanceof P&&(n.code.startsWith("E_COLUMN")||n.code==="E_DUPLICATE_ROLE")?new P("E_BAD_SERIALIZATION",`${e}: ${n.message}`,{ref:e,reason:n.message,cause:n.code,...n.details}):n instanceof Error?n:re(e,String(n))}class q1{constructor(e,t){this.ranges=[],this.skipped=[],this.regions=e,this.options=t}get structure(){return this.options.level!=="none"}get full(){return this.options.level==="full"}array(e,t,r,o){const s=Xs(e,t);if(s.dtype!==r)throw re(t,`expected dtype ${r}, found ${s.dtype}`,{expected:r,found:s.dtype});const i=this.regions[s.buffer];if(i===void 0)throw re(t,`buffer index ${s.buffer} is out of range (${this.regions.length} buffers)`,{found:s.buffer,buffers:this.regions.length});const a=j1(s.dtype);if(s.byteOffset%a!==0)throw re(t,`byteOffset ${s.byteOffset} is not a multiple of ${a}`,{byteOffset:s.byteOffset,elementSize:a});if(s.byteLength!==s.length*a)throw re(t,`byteLength ${s.byteLength} is not length ${s.length} * ${a}`,{byteLength:s.byteLength,length:s.length,elementSize:a});if(s.byteOffset+s.byteLength>i.byteLength)throw re(t,`range [${s.byteOffset}, ${s.byteOffset+s.byteLength}) exceeds the buffer`,{byteOffset:s.byteOffset,byteLength:s.byteLength,bufferByteLength:i.byteLength});const c=i.locate(s.byteOffset,s.byteLength);if(c!==null&&c.byteOffset%a===0)return this.ranges.push({buffer:c.buffer,start:c.byteOffset,end:c.byteOffset+s.byteLength,kind:o,path:t}),Kd(s.dtype,c.buffer,c.byteOffset,s.length);const l=i.read(s.byteOffset,s.byteLength);return Kd(s.dtype,l.buffer,0,s.length)}u32(e,t,r){return this.array(e,t,"u32",r)}utf8(e,t,r,o,s=!1){const i=vt(e,t),a=this.u32(i.offsets,`${t}.offsets`,o),c=this.array(i.utf8,`${t}.utf8`,"utf8",o);if(a.length===0)throw re(`${t}.offsets`,"a Utf8 store needs at least one offset");if((this.structure||s)&&ha(a,c,r??a.length-1,t),this.full){const l=Wn.fromEncoded(a,c).firstMalformedRow();if(l!==-1)throw re(t,`malformed UTF-8 in row ${l}`,{row:l})}return{offsets:a,utf8:c}}checkOverlaps(){const e=this.ranges.filter(t=>(t.kind==="core"||t.kind==="immutable")&&t.end>t.start);for(const t of this.ranges)if(!(t.kind!=="mutable"||t.end===t.start)){for(const r of e)if(r.buffer===t.buffer&&t.start<r.end&&r.start<t.end)throw re(t.path,`mutable column overlaps ${r.path}`,{overlaps:r.path})}}column(e,t,r,o,s){const i=vt(e,s),a=vt(i.meta,`${s}.meta`),c=Xo(a.name,`${s}.meta.name`);if(this.skipUnknownDtype(a,c,t,r,s))return null;const l=this.columnMeta(a,c,t,s),u=l.mutable?"mutable":"immutable",d=Gr(l,o,i.validity===null||i.validity===void 0?null:this.u32(i.validity,`${s}.validity`,u)),f=i.nullCount;switch(l.dtype){case"f32":case"f64":case"i32":case"u32":d.data=this.array(i.data,`${s}.data`,l.dtype,u);break;case"u8":{const g=this.array(i.data,`${s}.data`,"u8",u);d.data=Ds(g)?g:H0(g);break}case"bool":d.data=this.u32(i.data,`${s}.data`,u);break;case"dict":{d.data=this.u32(i.data,`${s}.data`,u);const g=this.utf8(i.dictionary,`${s}.dictionary`,null,u,!0);d.dictionary=fa(g.utf8,g.offsets,0,g.offsets.length-1);break}case"string":{const g=this.utf8(i.strings,`${s}.strings`,o,u);d.offsets=g.offsets,d.utf8=g.utf8;break}case"list":{const g=this.u32(i.offsets,`${s}.offsets`,u);if(g.length!==o+1)throw re(`${s}.offsets`,`expected ${o+1} offsets, found ${g.length}`,{expected:o+1,found:g.length});d.offsets=g;const w=this.column(i.child,t,r,g[o],`${s}.child`);if(w===null||w.dtype==="list")throw re(`${s}.child`,"a list column needs a non-list child column");d.child=w;break}case"json":d.values=this.jsonRows(i.jsonText,o,`${s}.jsonText`,u);break;default:{const g=l.dtype;throw re(`${s}.meta.dtype`,`unknown dtype ${g}`,{dtype:g})}}let h;try{h=Tt(d)}catch(g){throw Ka(g,s)}if(this.structure&&h.nullCount!==f)throw re(`${s}.nullCount`,`manifest says ${String(f)}, the bitmap says ${h.nullCount}`,{expected:h.nullCount,found:f});return h}skipUnknownDtype(e,t,r,o,s){const{dtype:i,itemDtype:a}=e;if(!(!Vd(i)||i==="list"&&!Vd(a)))return!1;const l=i==="list"?a:i;if(this.options.unknownColumns==="skip")return this.skipped.push({domain:r,table:o,name:t,dtype:String(l)}),!0;throw new P("E_UNSUPPORTED",`column "${t}" has unknown dtype ${String(l)}`,{dtype:l,column:t,ref:s})}columnMeta(e,t,r,o){const s=`${o}.meta`,i=(l,u)=>{const d=e[l];return d==null?void 0:u(d,`${s}.${l}`)},a=(l,u)=>{if(typeof l!="number")throw re(u,"expected a number",{found:l});return l},c={name:t,dtype:e.dtype,components:i("components",a),itemDtype:i("itemDtype",l=>l),itemComponents:i("itemComponents",a),nullable:i("nullable",_r),mutable:i("mutable",_r),role:i("role",Xo),refersTo:i("refersTo",l=>l),unique:i("unique",_r),default:Hn(e.default,`${s}.default`),fill:Hn(e.fill,`${s}.fill`),options:i("options",(l,u)=>Hn(l,u)),origin:i("origin",l=>l),dynamic:i("dynamic",_r),extra:i("extra",(l,u)=>Hn(l,u))};try{return ht(t,r,c)}catch(l){throw Ka(l,o)}}jsonRows(e,t,r,o){const s=this.utf8(e,r,t,o,!0),i=fa(s.utf8,s.offsets,0,t),a=new Array(t);for(let c=0;c<t;c++){const l=i[c];a[c]=l===""?void 0:Hn(qd(l,`${r}[${c}]`),`${r}[${c}]`)}return a}table(e,t,r,o,s){const i=Ks(e,s),a=[],c=new Set;for(let l=0;l<i.length;l++){const u=this.column(i[l],t,r,o,`${s}[${l}]`);if(u!==null){if(c.has(u.meta.name))throw re(`${s}[${l}].meta.name`,`column "${u.meta.name}" is declared twice`,{column:u.meta.name});c.add(u.meta.name),a.push(u)}}try{return new wn({domain:t,rowCount:o,columns:a})}catch(l){throw Ka(l,s)}}ids(e){const t=vt(e,"ids"),r=t.kind;if(typeof r!="string"||!D1.has(r))throw new P("E_UNSUPPORTED",`unknown id map kind ${Hr(r)}`,{kind:r,ref:"ids.kind"});const o=r,s=Nn(t.size,"ids.size"),i=t.offset??0;if(typeof i!="number")throw re("ids.offset","expected a number",{found:i});const c={kind:o,size:s,offset:o==="identity"?i:0,values:null,tags:null,numbers:null,offsets:null,utf8:null};switch(o){case"identity":break;case"dense":c.values=this.u32(t.values,"ids.values","immutable");break;case"numeric":c.values=this.array(t.values,"ids.values","f64","immutable");break;case"string":{c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}case"mixed":{c.tags=this.array(t.tags,"ids.tags","u8","immutable"),c.numbers=this.array(t.numbers,"ids.numbers","f64","immutable"),c.offsets=this.u32(t.offsets,"ids.offsets","immutable"),c.utf8=this.array(t.utf8,"ids.utf8","utf8","immutable");break}default:{const l=o;throw new P("E_UNSUPPORTED",`unknown id map kind ${l}`,{kind:l})}}return $y(c,this.options.level)}views(e){const t=new Map;if(e==null)return t;const r=vt(e,"views");for(const o of Object.keys(r)){const s=vt(r[o],`views.${o}`),i=new Map;for(const a of Object.keys(s)){const c=`views.${o}.${a}`,l=Xs(s[a],c);i.set(a,this.array(l,c,l.dtype,"view"))}t.set(o,i)}return t}}function Xt(n,e,t,r,o,s){const i=`views.${e}.${t}`,a=n.get(t);if(a===void 0){if(s)throw re(i,"the carried view is missing this member");return null}if(!(a instanceof r))throw re(i,`expected ${r.name}, found ${a.constructor.name}`,{expected:r.name,found:a.constructor.name});if(a.length!==o)throw re(i,`expected ${o} entries, found ${a.length}`,{expected:o,found:a.length});return a}function Yd(n,e,t,r){return Xt(n,e,"data",t,r,!0)}function H1(n,e,t){let r=null;const o={snapshot:n,verify:t,facts:()=>(r??=new s1(n),r)};for(const[s,i]of e)Y1(s,n.directed)||X1(o,s,i)}const K1=new Set(["reverse","inDegree","weightedInDegree","reverseDegreeOrder"]);function Y1(n,e){return e?n==="mate":K1.has(n)}function X1(n,e,t){const{snapshot:r}=n;switch(e){case"reverse":Q1(n,t);break;case"coo":J1(n,t);break;case"edgeList":Z1(n,t);break;case"outDegree":Kr(n,"outDegree",t,r.nodeCount,o=>{i1(r,o)});break;case"degree":Kr(n,"degree",t,r.nodeCount,o=>{c1(r,n.facts(),o)});break;case"selfLoopsPerNode":Kr(n,"selfLoopsPerNode",t,r.nodeCount,o=>{l1(n.facts(),o)});break;case"inDegree":Kr(n,"inDegree",t,r.nodeCount,o=>{a1(n.facts(),o)});break;case"selfLoopArcs":Kr(n,"selfLoopArcs",t,r.selfLoopCount,o=>{u1(r,n.facts(),o)});break;case"mate":Kr(n,"mate",t,r.arcCount,o=>{h1(r,n.facts(),o)});break;case"weightedOutDegree":case"weightedInDegree":case"weightedDegree":case"selfLoopWeight":e2(n,e,t);break;case"degreeOrder":case"reverseDegreeOrder":t2(n,e,t);break}}function Xd(n,e,t){if(t!==null&&n.weights===null)throw re(`views.${e}.weights`,"weights carried for an unweighted snapshot")}function Q1(n,e){const{snapshot:t}=n,{nodeCount:r,arcCount:o}=t,s=Xt(e,"reverse","rowPtr",Uint32Array,r+1,!0),i=Xt(e,"reverse","colIdx",Uint32Array,o,!0),a=Xt(e,"reverse","fwdArc",Uint32Array,o,!0),c=Xt(e,"reverse","weights",Float32Array,o,t.weights!==null);Xd(t,"reverse",c);const l=new Ko(t,s,i,c,a);n.verify&&p1(t,n.facts(),l),Yr(t,"reverse",l)}function J1(n,e){const{snapshot:t}=n,r=Xt(e,"coo","src",Uint32Array,t.arcCount,!0);n.verify&&d1(n.facts(),r),Yr(t,"coo",yd(t,r))}function Z1(n,e){const{snapshot:t}=n,{edgeCount:r}=t,o=t.flags.arcToEdgeIsIdentity,s=Xt(e,"edgeList","src",Uint32Array,r,!0),i=Xt(e,"edgeList","dst",Uint32Array,r,!o),a=Xt(e,"edgeList","weights",Float32Array,r,t.weights!==null&&!o);Xd(t,"edgeList",a),n.verify&&f1(t,n.facts(),s,i,a),Yr(t,"edgeList",za(t,s,i??t.colIdx,a??t.weights))}function Kr(n,e,t,r,o){const s=Yd(t,e,Uint32Array,r);n.verify&&o(s),Yr(n.snapshot,e,s)}function e2(n,e,t){const{snapshot:r}=n,o=Yd(t,e,Float64Array,r.nodeCount);if(n.verify){m1(e,o,r[e]());return}Yr(r,e,o)}function t2(n,e,t){const{snapshot:r}=n,{nodeCount:o}=r,s=Xt(t,e,"perm",Uint32Array,o,!0),i=Xt(t,e,"segmentOffsets",Uint32Array,5,!0);if(n.verify){const a=e==="degreeOrder"?Ar(r.rowPtr,o):n.facts().inDegree;g1(e,a,s,i)}Yr(r,e,Object.freeze({perm:s,segmentOffsets:i}))}function n2(n){const e=vt(n,"core"),t=r=>{const o=e[r];return o==null?null:Xs(o,`core.${r}`)};return{rowPtr:Xs(e.rowPtr,"core.rowPtr"),colIdx:t("colIdx"),weights:t("weights"),arcToEdge:t("arcToEdge"),edgeToArc:t("edgeToArc")}}function r2(n,e,t,r){const o=n.u32(e.rowPtr,"core.rowPtr","core");let s;if(e.colIdx===null){if(t.arcs!==0)throw re("core.colIdx",`null although counts.arcs is ${t.arcs}`);s=new Uint32Array(0)}else s=n.u32(e.colIdx,"core.colIdx","core");let i=null;if(e.weights!==null){if(!r.weighted)throw re("core.weights","present although flags.weighted is false");i=n.array(e.weights,"core.weights","f32","core")}else if(r.weighted){if(t.arcs!==0)throw re("core.weights",`null although flags.weighted is true and counts.arcs is ${t.arcs}`);i=new Float32Array(0)}const a=r.arcToEdgeIsIdentity,c=(l,u,d)=>{if(l!==null){if(a)throw re(`core.${u}`,"present although flags.arcToEdgeIsIdentity is true");return n.u32(l,`core.${u}`,"core")}if(a)return null;if(d!==0)throw re(`core.${u}`,`null although the permutation is not the identity and the count is ${d}`);return new Uint32Array(0)};return{rowPtr:o,colIdx:s,weights:i,arcToEdge:c(e.arcToEdge,"arcToEdge",t.arcs),edgeToArc:c(e.edgeToArc,"edgeToArc",t.edges)}}function o2(n,e,t,r,o){if(e===null||t===null||t.length===0||!(e.buffer===r.buffer&&e.byteOffset>=r.byteOffset&&e.byteOffset+e.byteLength<=r.byteOffset+r.byteLength))return null;const i=e.byteOffset-r.byteOffset;if(i%ft!==0)throw re(`core.${n}`,`inside the arena at offset ${i}, not a multiple of ${ft}`,{byteOffset:i});if(t.buffer!==o.buffer||t.byteOffset!==o.byteOffset+i)throw re(`core.${n}`,"the arena describes a segment the array is not a view of");return Object.freeze({byteOffset:o.byteOffset+i,byteLength:e.byteLength})}function s2(n,e,t,r,o){if(n==null)return null;const s=vt(n,"arena"),i=Nn(s.buffer,"arena.buffer"),a=Nn(s.byteOffset,"arena.byteOffset"),c=Nn(s.byteLength,"arena.byteLength"),l=e[i];if(l===void 0)throw re("arena.buffer",`buffer index ${i} is out of range`,{found:i});if(a+c>l.byteLength)throw re("arena",`range [${a}, ${a+c}) exceeds the buffer`,{byteOffset:a,byteLength:c,bufferByteLength:l.byteLength});const u=l.locate(a,c);if(u===null)return null;const d={rowPtr:null,colIdx:null,weights:null,arcToEdge:null,edgeToArc:null};let f=0;const h={buffer:i,byteOffset:a,byteLength:c},g=Ho;for(const w of g){const p=o2(w,t[w],r[w],h,u);p!==null&&(d[w]=p,(w==="rowPtr"||w==="colIdx"||w==="weights")&&(f=p.byteOffset-u.byteOffset+p.byteLength))}if(o&&s.hotByteLength!==f)throw re("arena.hotByteLength",`manifest says ${String(s.hotByteLength)}, the segments say ${f}`,{expected:f,found:s.hotByteLength});return Object.freeze({buffer:u.buffer,byteOffset:u.byteOffset,byteLength:c,alignment:ft,segments:Object.freeze(d),hotByteLength:f})}function i2(n){const e=vt(n,"flags"),t=r=>_r(e[r],`flags.${r}`);return{multigraph:t("multigraph"),hasSelfLoops:t("hasSelfLoops"),arcToEdgeIsIdentity:t("arcToEdgeIsIdentity"),weighted:t("weighted"),allWeightsOne:t("allWeightsOne"),nonNegativeWeights:t("nonNegativeWeights"),finiteWeights:t("finiteWeights")}}function a2(n,e){if(n==null)return null;const t=vt(n,e),r=o=>Cn(t[o],`${e}.${o}`);return{format:r("format"),id:r("id"),title:r("title"),type:r("type"),namespace:r("namespace")}}function c2(n){const e=vt(n,"meta"),t=e.keywords??[],r=Ks(t,"meta.keywords").map((s,i)=>Xo(s,`meta.keywords[${i}]`)),o=Hn(e.extra??{},"meta.extra");if(!kn(o))throw re("meta.extra","expected an object");return Object.freeze({name:Cn(e.name,"meta.name"),description:Cn(e.description,"meta.description"),creator:Cn(e.creator,"meta.creator"),created:Cn(e.created,"meta.created"),modified:Cn(e.modified,"meta.modified"),keywords:Object.freeze(r),sourceFormat:Cn(e.sourceFormat,"meta.sourceFormat"),sourceVersion:Cn(e.sourceVersion,"meta.sourceVersion"),idType:Ys(e.idType,"meta.idType",L1),timeFormat:Ys(e.timeFormat,"meta.timeFormat",M1),timeRepresentation:Ys(e.timeRepresentation,"meta.timeRepresentation",U1),mode:Ys(e.mode,"meta.mode",F1),declaredMultigraph:z1(e.declaredMultigraph,"meta.declaredMultigraph"),weightOrigin:a2(e.weightOrigin,"meta.weightOrigin"),extra:Object.freeze(o)})}function Qd(n){if(n.format!==la)throw re("format",`expected "${la}", found ${Hr(n.format)}`,{found:n.format});const e=Ks(n.wire,"wire"),t=e[0],r=e[1];if(typeof t!="number"||typeof r!="number"||!Number.isInteger(t)||!Number.isInteger(r))throw re("wire","expected [major, minor] integers",{found:n.wire});if(t!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${t} is not supported (reader: ${zn})`,{kind:"wire",found:t,supported:zn});if(n.formatVersion!==Mr)throw new P("E_UNSUPPORTED_VERSION",`formatVersion ${Hr(n.formatVersion)} is not supported (reader: ${Mr})`,{kind:"format",found:n.formatVersion,supported:Mr});return[t,r]}function l2(n,e,t,r){const o=vt(n,"manifest");Qd(o);const s=new q1(e,t),i=_r(o.directed,"directed"),a=vt(o.counts,"counts"),c={nodes:Nn(a.nodes,"counts.nodes"),edges:Nn(a.edges,"counts.edges"),arcs:Nn(a.arcs,"counts.arcs"),selfLoops:Nn(a.selfLoops,"counts.selfLoops")},l=i2(o.flags);if(l.arcToEdgeIsIdentity&&(!i||c.arcs!==c.edges))throw re("flags.arcToEdgeIsIdentity","set on an undirected graph or with arcs !== edges");const u=n2(o.core),d=r2(s,u,c,l),f=s2(o.arena,e,u,d,s.structure),h=s.ids(o.ids),g=s.table(o.nodeColumns??[],"node",null,c.nodes,"nodeColumns"),w=s.table(o.edgeColumns??[],"edge",null,c.edges,"edgeColumns"),p=s.table(o.graphColumns??[],"graph",null,1,"graphColumns"),m=new Map,y=Ks(o.extensions??[],"extensions");for(let I=0;I<y.length;I++){const k=`extensions[${I}]`,N=vt(y[I],k),C=Xo(N.name,`${k}.name`);if(m.has(C))throw re(`${k}.name`,`extension table "${C}" appears twice`,{table:C});const O=Nn(N.rowCount,`${k}.rowCount`);m.set(C,s.table(N.columns,"extension",C,O,`${k}.columns`))}let b=c2(o.meta??{});if(s.skipped.length>0){const I=Object.freeze(s.skipped.map(k=>Object.freeze({...k})));b=Object.freeze({...b,extra:Object.freeze({...b.extra,[B1]:I})})}const v=s.views(o.views);s.structure&&s.checkOverlaps();const A={label:Cn(o.label,"label"),serial:null,directed:i,nodeCount:c.nodes,edgeCount:c.edges,arcCount:c.arcs,selfLoopCount:c.selfLoops,rowPtr:d.rowPtr,colIdx:d.colIdx,weights:d.weights,arcToEdge:d.arcToEdge,edgeToArc:d.edgeToArc,flags:l,ids:h,nodes:g,edges:w,graph:p,extensions:m,meta:b,arena:f,checksum:!1},E=pf(A);return t.level==="full"?E.validate({level:"full"}):t.level==="structure"&&E.validate({level:"structure"}),t.level!=="full"&&H1(E,v,t.level==="structure"),E}const Tn=16,u2=new TextDecoder("utf-8",{fatal:!0});function Jd(n,e){const t=new ja("container"),{manifest:r}=Ha(n,t,e.includeViews,!0),o=O1(r);return{manifestBytes:o,regionStart:hr(Tn+o.byteLength,ft),segments:t.segments,regionLength:t.regionLength}}function Zd(n,e){n.set(ua,0);const t=new DataView(n.buffer,n.byteOffset,n.byteLength);t.setUint16(4,zn,!0),t.setUint16(6,_u,!0),new Uint32Array(n.buffer,n.byteOffset+8,1)[0]=da,t.setUint32(12,e,!0)}function ef(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function d2(n,e={}){const t=Jd(n,e),r=new Uint8Array(t.regionStart+t.regionLength);Zd(r,t.manifestBytes.byteLength),r.set(t.manifestBytes,Tn);for(const o of t.segments)r.set(ef(o.view),t.regionStart+o.ref.byteOffset);return r}function*f2(n){const e=new Uint8Array(n.regionStart);Zd(e,n.manifestBytes.byteLength),e.set(n.manifestBytes,Tn),yield e;for(const t of n.segments){if(t.ref.byteLength===0)continue;const r=new Uint8Array(hr(t.ref.byteLength,ft));r.set(ef(t.view)),yield r}}function h2(n,e={}){return f2(Jd(n,e))}function g2(n,e){if(e<Tn)throw re("header",`truncated: ${e} bytes, expected at least ${Tn}`,{byteLength:e});for(let a=0;a<ua.length;a++)if(n[a]!==ua[a])throw re("magic","not a GSNP container",{found:Array.from(n.subarray(0,4))});const t=new DataView(n.buffer,n.byteOffset,n.byteLength),r=t.getUint16(4,!0),o=t.getUint16(6,!0);if(r!==zn)throw new P("E_UNSUPPORTED_VERSION",`wire major ${r} is not supported (reader: ${zn})`,{kind:"wire",found:r,supported:zn});const s=t.getUint32(8,Eu);if(s!==da)throw re("endianness",`probe reads 0x${s.toString(16)}; the container was written on another endianness`,{found:s,expected:da});const i=t.getUint32(12,!0);if(Tn+i>e)throw re("manifest",`truncated: ${i} manifest bytes declared, ${e} bytes in total`,{manifestLength:i,byteLength:e});return{major:r,minor:o,manifestLength:i}}function w2(n,e){let t;try{t=u2.decode(n)}catch{throw re("manifest","not valid UTF-8")}const r=qd(t,"manifest");if(typeof r!="object"||r===null||Array.isArray(r))throw re("manifest","expected an object");const o=r,[s,i]=Qd(o);if(s!==e.major||i!==e.minor)throw re("wire",`manifest says [${s}, ${i}], the header says [${e.major}, ${e.minor}]`,{found:[s,i],header:[e.major,e.minor]});return o}function p2(n,e){const t=W1(e,"full"),r=n instanceof Uint8Array?n:new Uint8Array(n),o=g2(r,r.byteLength),s=w2(r.subarray(Tn,Tn+o.manifestLength),o),i=hr(Tn+o.manifestLength,ft),a=Math.max(0,r.byteLength-i),{buffer:c}=r;let l;if(!t.copy&&!V1(c)&&r.byteOffset%8===0)l=Hd(c,r.byteOffset+i,a);else{const u=new Uint8Array(hr(a,ft));a>0&&u.set(r.subarray(i)),l=Hd(u.buffer,0,a)}return l2(s,[l],t)}function m2(n,e,t){for(let r=1;r<t;r++){const o=n[r],s=n[r-1];if(o<s||o===s&&e[r]<e[r-1])return!1}return!0}function y2(n,e){return new P("E_INVALID_WEIGHT",`edge ${n} has a NaN weight`,{edge:n,weight:e})}function b2(n,e,t){let r=1/0,o=-1/0;for(let s=0;s<e;s++){const i=Math.fround(n[s]);if(Number.isNaN(i))throw y2(s,n[s]);i<r&&(r=i,t[0]=i),i>o&&(o=i,t[1]=i)}}function v2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c&&s++}return s}function A2(n,e,t,r,o){let s=0;for(let i=0;i<t;i++){const a=n[i],c=e[i];r[c+1]++,o[a+1]++,a===c?s++:(r[a+1]++,o[c+1]++)}return s}function tf(n,e){for(let t=0;t<e;t++)n[t+1]+=n[t]}function E2(n,e,t,r){let o=!1;for(let s=0;s<t;s++){const i=e[s];r[s]=i,s>0&&n[s]===n[s-1]&&e[s-1]===i&&(o=!0)}return o}function _2(n,e,t,r,o){for(let s=0;s<t;s++){const i=2*r[e[s]]++;o[i]=n[s],o[i+1]=s}}function I2(n,e,t,r,o,s){for(let i=0;i<t;i++){const a=n[i],c=e[i],l=r[c]++;if(o[2*l]=a,o[2*l+1]=i,s[l>>>5]|=1<<(l&31),a!==c){const u=2*r[a]++;o[u]=c,o[u+1]=i}}}function k2(n,e,t,r,o,s){for(let i=0;i<n;i++){const a=2*e[i+1];for(let c=2*e[i];c<a;c+=2){const l=r[t[c]]++;o[l]=i,s[l]=t[c+1]}}}function S2(n,e,t,r,o,s){const{targetStart:i,byTarget:a,declared:c}=e;for(let l=0;l<n;l++){const u=i[l+1];for(let d=i[l];d<u;d++){const f=a[2*d+1],h=t[a[2*d]]++;r[h]=l,o[h]=f,(c[d>>>5]>>>(d&31)&1)===1&&(s[f]=h)}}}function P2(n,e){const t=n.length;for(let r=0;r<t;r++)e[n[r]]=r}function x2(n,e,t){const r=n.length;for(let o=0;o<r;o++)t[o]=e[n[o]]}function C2(n,e,t){for(let r=0;r<t;r++){const o=n[r+1];for(let s=n[r]+1;s<o;s++)if(e[s]===e[s-1])return!0}return!1}function Ya(n,e){const{directed:t,nodeCount:r,edgeCount:o,src:s,dst:i}=n,a=n.weights;let c=!0,l=!0,u=!0;if(a!==null&&o>0){const k=new Float64Array([1/0,-1/0]);b2(a,o,k);const N=k[0],C=k[1];c=N===1&&C===1,l=N>=0,u=N>-1/0&&C<1/0}const d=new Uint32Array(r+1),f=new Uint32Array(r+1),h=t?v2(s,i,o,d,f):A2(s,i,o,d,f),g=t?o:2*o-h,w=t&&m2(s,i,o),p=wb({nodeCount:r,arcCount:g,edgeCount:o,weighted:a!==null,identity:w},e),{rowPtr:m,colIdx:y,weights:b,arcToEdge:v,edgeToArc:A}=p;tf(f,r),m.set(f);let E;if(w)E=E2(s,i,o,y),b!==null&&a!==null&&b.set(a.subarray(0,o));else if(v!==null&&A!==null){tf(d,r);const k=f;k.set(d);const N=new Uint32Array(2*g);let C=null;t?_2(s,i,o,k,N):(C=new Uint32Array(g+31>>>5),I2(s,i,o,k,N,C)),k.set(m),C===null?(k2(r,d,N,k,y,v),P2(v,A)):S2(r,{targetStart:d,byTarget:N,declared:C},k,y,v,A),b!==null&&a!==null&&x2(v,a,b),E=C2(m,y,r)}else throw new P("E_UNSUPPORTED","unreachable: a non-identity core without permutation arrays",{directed:t,arcCount:g});const I=Object.freeze({multigraph:E,hasSelfLoops:h>0,arcToEdgeIsIdentity:w,weighted:b!==null,allWeightsOne:c,nonNegativeWeights:l,finiteWeights:u});return{core:p,arcCount:g,selfLoopCount:h,flags:I}}function N2(n,e){return n instanceof Uint8Array?mr(e):n instanceof Uint32Array?new Uint32Array(e):n instanceof Int32Array?new Int32Array(e):n instanceof Float32Array?new Float32Array(e):new Float64Array(e)}function T2(n,e){const t=n.validity;let r=null,o=0;for(let s=0;s<e.length;s++){const i=e[s];i!==x&&(t===null||Le(t,i))||(r??=In(e.length,!0),Kt(r,s),o++)}return{validity:r,nullCount:o}}function Xa(n,e){return n.nullable||e===0?n:Object.freeze({...n,nullable:!0})}function O2(n,e){for(let t=0;t<e.length;t++){const r=e[t];if(r!==x&&r>=n.length)throw new P("E_INDEX_RANGE",`indexMap[${t}] = ${r} is outside the column of ${n.length} rows`,{index:t,found:r,length:n.length,column:n.meta.name})}}function $2(n,e,t){const{length:r}=e,{components:o,fill:s}=t,i=N2(n.data,r*o);typeof s=="number"&&s!==0&&i.fill(s);for(let a=0;a<r;a++){const c=e[a];if(c!==x)for(let l=0;l<o;l++)i[a*o+l]=n.data[c*o+l]}return i}function R2(n,e,t){const{length:r}=e,o=new Uint32Array(Fe(r)).fill(t.fill===!0?4294967295:0);for(let s=0;s<r;s++){const i=e[s];i!==x&&(Le(n.data,i)?Ht(o,s):Kt(o,s))}return o}function D2(n,e,t){const r=typeof t.fill=="string"?n.codeOf(t.fill):x,o=r===x?0:r,s=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const a=e[i];s[i]=a===x?o:n.codes[a]}return s}function L2(n,e,t){const r=typeof t.fill=="string"?t.fill:"",o=new Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];o[s]=i===x?r:n.valueAt(i)}return o}function M2(n,e){const t=new Uint32Array(e.length+1);let r=0;for(let o=0;o<e.length;o++){const s=e[o];s!==x&&(r+=n[s+1]-n[s]),t[o+1]=r}return t}function U2(n,e,t){const r=new Uint32Array(t);let o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i!==x)for(let a=n[i];a<n[i+1];a++)r[o++]=a}return r}function F2(n,e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const o=e[r];t[r]=o===x?void 0:n.values[o]}return t}function B2(n,e,t){const{meta:r}=n,{dtype:o}=e;switch(o){case"f32":case"f64":case"i32":case"u32":case"u8":n.data=$2(e,t,r);return;case"bool":n.data=R2(e,t,r);return;case"dict":n.data=D2(e,t,r);return;case"string":n.offsets=null,n.utf8=null,n.strings=L2(e,t,r);return;case"list":{const s=M2(e.offsets,t);n.offsets=s,n.child=Qo(e.child,U2(e.offsets,t,s[t.length]));return}case"json":n.values=F2(e,t);return;default:{const s=o;throw new P("E_COLUMN_TYPE",`unknown dtype ${s}`,{dtype:s})}}}function Qo(n,e){O2(n,e);const{validity:t,nullCount:r}=T2(n,e),o={...Us(n),meta:Xa(n.meta,r),length:e.length,validity:t};return B2(o,n,e),Tt(o)}function nf(n,e){if(n.meta.refersTo===null)return n;const t=r=>r===x||r>=e.length?x:e[r];if(n.dtype==="u32"){const{length:r}=n,o=new Uint32Array(r);let s=n.validity===null?null:n.validity.slice(),{nullCount:i}=n;for(let c=0;c<r;c++){const l=t(n.data[c]);o[c]=l,l===x&&(s===null||Le(s,c))&&(s??=In(r,!0),Kt(s,c),i++)}const a={...Us(n),meta:Xa(n.meta,i),data:o,validity:s};return Tt(a)}if(n.dtype==="list"&&n.child.dtype==="u32"){const{length:r,offsets:o,child:s}=n,i=new Array(r);let a=n.validity===null?null:n.validity.slice(),{nullCount:c}=n;for(let f=0;f<r;f++){const h=[],g=o[f],w=o[f+1];for(let p=g;p<w;p++){const m=t(s.data[p]);m!==x&&h.push(m)}i[f]=h,w>g&&h.length===0&&(a===null||Le(a,f))&&(a??=In(r,!0),Kt(a,f),c++)}const l=Xa(n.meta,c),u=Vo(Object.freeze({...l,nullable:!0}),i),d={...Us(u),meta:l,validity:a};return Tt(d)}throw new P("E_COLUMN_TYPE",`column "${n.meta.name}" has refersTo but is not u32 or a list of u32`,{column:n.meta.name,field:"refersTo"})}function rf(n,e){return n.refersTo==="node"?e.node:n.refersTo==="edge"?e.edge:null}function Qa(n,e,t,r){const o=n.rowCount,s=[];for(const i of n){const a=rf(i.meta,r);let c=i;a!==null&&(c=nf(i,a)),s.push(c)}return new wn({domain:n.domain,rowCount:o,columns:s})}function of(n,e,t){const r=[];for(const o of n){const s=Qo(o,e),i=rf(o.meta,t);r.push(i===null?s:nf(s,i))}return new wn({domain:n.domain,rowCount:e.length,columns:r})}function At(n,e){return In(n,e===!0)}function _e(n,e){return Le(n,e)}function pn(n,e,t){ba(n,e,t)}function z2(n,e){return gr(n,e)}function sf(n,e){return X0(n,e)}function Qs(n,e,t){const r=Fe(e);if(n.length<r)throw new P("E_MASK_LENGTH",`mask over ${t} has ${n.length} words; ${r} needed for ${e} ${t}`,{found:n.length,required:r,length:e})}const af=Object.freeze({droppedEdges:0,mergedEdges:0});function cf(){return{parts:null,nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function Jo(n,e={}){const t=Ya(n,e.arena!==!1),{core:r}=t;return{arcCount:t.arcCount,selfLoopCount:t.selfLoopCount,rowPtr:r.rowPtr,colIdx:r.colIdx,weights:r.weights,arcToEdge:r.arcToEdge,edgeToArc:r.edgeToArc,flags:t.flags,arena:r.arena}}function Zo(n,e,t){return{label:n.label,serial:null,directed:t.directed,nodeCount:t.nodeCount,edgeCount:t.edgeCount,arcCount:e.arcCount,selfLoopCount:e.selfLoopCount,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,flags:e.flags,ids:t.ids,nodes:t.nodes,edges:t.edges,graph:n.graph,extensions:t.extensions,meta:n.meta,arena:e.arena,checksum:!1}}function es(n,e,t){if(e===null&&t===null||n.extensions.size===0)return n.extensions;const r=new Map;for(const[o,s]of n.extensions)r.set(o,Qa(s,null,s.rowCount,{node:e,edge:t}));return r}function G2(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++){const o=n[r];o!==x&&t[o]===x&&(t[o]=r)}return t}function Js(n){const e=n.length,t=new Uint32Array(e).fill(x);let r=0,o=0,s=0;for(let a=0;a<e;a++)n[a]===a?t[a]=r++:n[a]===x?o++:s++;if(o===0&&s===0)return{count:r,remap:null,origin:null,dropped:o,merged:s};const i=new Uint32Array(e);for(let a=0;a<e;a++){const c=n[a];i[a]=c===x?x:t[c]}return{count:r,remap:i,origin:G2(i,r),dropped:o,merged:s}}function W2(n,e){return n.length===e&&qr(n)}function ts(n,e,t){const{count:r,origin:o}=e,s=new Uint32Array(r),i=new Uint32Array(r);for(let a=0;a<r;a++){const c=o===null?a:o[a];s[a]=t===null?n.src[c]:t[n.src[c]],i[a]=t===null?n.dst[c]:t[n.dst[c]]}return{src:s,dst:i}}function Ja(n,e){if(e!==void 0)for(const t of Object.keys(e))zt(`${n}.${t}`,e[t],Sy)}function ns(n,e,t){const{count:r,remap:o,origin:s}=e;if(n===null){if(t!=="sum")return null;const a=new Float32Array(r);if(o===null)return a.fill(1),a;for(let c=0;c<o.length;c++)o[c]!==x&&a[o[c]]++;return a}if(o===null||s===null)return n;const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=n[s[a]];if(t==="first")return i;for(let a=0;a<o.length;a++){const c=o[a];if(c===x||s[c]===a)continue;const l=n[a];switch(t){case"last":i[c]=l;break;case"sum":i[c]+=l;break;case"min":l<i[c]&&(i[c]=l);break;case"max":l>i[c]&&(i[c]=l);break;default:{const u=t;throw new P("E_UNSUPPORTED",`unknown weight reducer ${String(u)}`,{reducer:u})}}}return i}function Zs(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=e(r)?r:x;return Js(t)}function V2(n,e,t){const{count:r,remap:o}=e,{components:s}=n.meta,i=s,a=new Float64Array(r*i),c=new Uint32Array(r),l=new Uint8Array(r),u=n.data,d=o===null?n.length:o.length;for(let y=0;y<d;y++){const b=o===null?y:o[y];if(!(b===x||!n.isSet(y))){c[b]++;for(let v=0;v<i;v++){const A=u[y*i+v],E=b*i+v;if(l[b]===0)a[E]=A;else switch(t){case"sum":case"mean":a[E]+=A;break;case"min":A<a[E]&&(a[E]=A);break;case"max":A>a[E]&&(a[E]=A);break;default:{const I=t;throw new P("E_UNSUPPORTED",`unknown reducer ${String(I)}`,{reducer:I})}}}l[b]=1}}if(t==="mean"){for(let y=0;y<r;y++)if(c[y]>1)for(let b=0;b<i;b++)a[y*i+b]/=c[y]}const h=t==="mean"||t==="sum"&&n.dtype!=="f32"&&n.dtype!=="f64"?"f64":n.dtype;let g;switch(h){case"f64":g=a;break;case"f32":g=new Float32Array(a);break;case"i32":g=new Int32Array(a);break;case"u32":g=new Uint32Array(a);break;case"u8":g=new Uint8Array(new ArrayBuffer(Math.ceil(r*i/4)*4),0,r*i),g.set(a);break;default:{const y=h;throw new P("E_COLUMN_TYPE",`cannot reduce a ${String(y)} column`,{dtype:y})}}let w=null,p=0;for(let y=0;y<r;y++)l[y]===0&&(w??=In(r,!0),Kt(w,y),p++);const m=ht(n.meta.name,n.meta.domain,{dtype:h,components:s,nullable:n.meta.nullable||p>0,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(m,r,w),data:g})}function j2(n,e){const{count:t,remap:r}=e,o=new Uint32Array(t);if(r===null)o.fill(1);else for(let i=0;i<r.length;i++)r[i]!==x&&o[r[i]]++;const s=ht(n.meta.name,n.meta.domain,{dtype:"u32",nullable:!1,role:n.meta.role??void 0,extra:n.meta.extra});return Tt({...Gr(s,t,null),data:o})}function Za(n,e,t){if(t==="drop"||n.meta.refersTo!==null)return null;const{count:r,remap:o,origin:s}=e;switch(t){case"first":return s===null?n:Qo(n,s);case"last":{if(o===null)return n;const i=new Uint32Array(r);for(let a=0;a<o.length;a++)o[a]!==x&&(i[o[a]]=a);return Qo(n,i)}case"count":return j2(n,e);case"sum":case"min":case"max":case"mean":{const{dtype:i}=n;switch(i){case"f32":case"f64":case"i32":case"u32":case"u8":return V2(n,e,t);case"bool":case"dict":case"string":case"list":case"json":throw new P("E_COLUMN_TYPE",`reducer "${t}" needs a numeric column; "${n.meta.name}" is ${i}`,{column:n.meta.name,dtype:i,reducer:t});default:{const a=i;throw new P("E_COLUMN_TYPE",`unknown dtype ${String(a)}`,{dtype:a})}}}default:{const i=t;throw new P("E_UNSUPPORTED",`unknown column reducer ${String(i)}`,{reducer:i})}}}function ei(n,e,t,r){const o={node:r,edge:e.remap};if(t===void 0||Object.keys(t).length===0)return e.origin===null?r===null?n.edges:Qa(n.edges,null,n.edgeCount,o):of(n.edges,e.origin,o);const s=[];for(const a of n.edges){const c=t[a.meta.name];if(c===void 0){const u=e.origin===null?a:Qo(a,e.origin);s.push(u);continue}const l=Za(a,e,c);l!==null&&s.push(l)}const i=new wn({domain:"edge",rowCount:e.count,columns:s});return Qa(i,null,e.count,o)}function lf(n,e,t){const r=Zs(n.edgeCount,t),{src:o,dst:s}=ts(e,r,null),i=ns(e.weights,r,"first"),a=Jo({directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,src:o,dst:s,weights:i}),c=ei(n,r,void 0,null);return{parts:Zo(n,a,{directed:n.directed,nodeCount:n.nodeCount,edgeCount:r.count,ids:n.ids,nodes:n.nodes,edges:c,extensions:es(n,null,r.remap)}),nodeOrigin:null,edgeOrigin:r.origin,nodeRemap:null,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:0}}}function q2(n,e,t){return Qs(t,n.edgeCount,"edges"),lf(n,e,r=>_e(t,r))}function H2(n,e){return lf(n,e,t=>e.src[t]!==e.dst[t])}function uf(n,e,t,r){return new P("E_INDEX_RANGE",`inducedSubgraph selection[${n}] = ${e} is ${r} (nodeCount ${t})`,{index:n,found:e,nodeCount:t,reason:r})}function K2(n,e){const{nodeCount:t}=n;if(e instanceof Uint32Array){const r=new Uint8Array(t),o=new Uint32Array(e.length);for(let s=0;s<e.length;s++){const i=e[s];if(i>=t)throw uf(s,i,t,"out of range");if(r[i]===1)throw uf(s,i,t,"repeated");r[i]=1,o[s]=i}return o}return Qs(e.mask,t,"nodes"),sf(e.mask,t)}function df(n,e){const t=new Uint32Array(e).fill(x);for(let r=0;r<n.length;r++)t[n[r]]=r;return t}function ff(n,e,t,r){const o=t===null?n.nodeCount:t.length,s=t===null?null:df(t,n.nodeCount),{src:i,dst:a}=ts(e,r,s),c=ns(e.weights,r,"first"),l=Jo({directed:n.directed,nodeCount:o,edgeCount:r.count,src:i,dst:a,weights:c}),u={node:s,edge:r.remap},d=t===null?n.nodes:of(n.nodes,t,u),f=t===null?n.ids:Gy(n.ids,t),h=ei(n,r,void 0,s);return{parts:Zo(n,l,{directed:n.directed,nodeCount:o,edgeCount:r.count,ids:f,nodes:d,edges:h,extensions:es(n,s,r.remap)}),nodeOrigin:t,edgeOrigin:r.origin,nodeRemap:s,edgeRemap:r.remap,blockSizes:null,report:{droppedEdges:r.dropped,mergedEdges:r.merged}}}function Y2(n,e,t){const r=K2(n,t),o=W2(r,n.nodeCount),s=o?null:r,i=o?null:df(r,n.nodeCount),a=i===null?Zs(n.edgeCount,()=>!0):Zs(n.edgeCount,c=>i[e.src[c]]!==x&&i[e.dst[c]]!==x);return ff(n,e,s,a)}function X2(n,e,t){const{nodeCount:r}=n;if(t.length!==r)throw new P("E_INVALID_PERMUTATION",`perm has ${t.length} entries, expected ${r}`,{expected:r,found:t.length});const o=new Uint8Array(r);for(let a=0;a<r;a++){const c=t[a];if(c>=r||o[c]===1)throw new P("E_INVALID_PERMUTATION",`perm[${a}] = ${c} is out of range or repeated (nodeCount ${r})`,{index:a,found:c,nodeCount:r});o[c]=1}const s=qr(t)?null:t.slice(),i=Zs(n.edgeCount,()=>!0);return ff(n,e,s,i)}function hf(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Q2(n,e,t,r,o){for(let s=0;s<o;s++){const i=e[t+s],a=e[r+s],c=Math.min(i,a),l=Math.max(i,a);n[c]=c,n[l]=c}}function J2(n,e,t={}){const r=t.reciprocal===!0,o=zt("weights",t.weights,Fs)??"first",{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i);for(let y=0;y<i;y++)u[y]=r&&e.src[y]!==e.dst[y]?x:y;for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if(A>y){const[I,k]=qs(a,c,A,y);Q2(u,l,v,I,Math.min(E-v,k-I))}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,o),w=Jo({directed:!1,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,void 0,null);return{parts:Zo(n,w,{directed:!1,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Z2(n,e){const{nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s}=n,i=e.arcToEdge,a=qr(i);let c=null,l=null;if(!a){c=i,l=new Uint32Array(r);for(let f=0;f<o;f++)l[i[f]]=f}const u=_d({directed:!0,nodeCount:t,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,selfLoopCount:s});return Gn(e.rowPtr.buffer),Gn(e.colIdx.buffer),e.weights!==null&&Gn(e.weights.buffer),c!==null&&Gn(c.buffer),{parts:{label:n.label,serial:null,directed:!0,nodeCount:t,edgeCount:r,arcCount:o,selfLoopCount:s,rowPtr:e.rowPtr,colIdx:e.colIdx,weights:e.weights,arcToEdge:c,edgeToArc:l,flags:u,ids:n.ids,nodes:n.nodes,edges:n.edges,graph:n.graph,extensions:n.extensions,meta:n.meta,arena:null,checksum:!1},nodeOrigin:null,edgeOrigin:null,nodeRemap:null,edgeRemap:null,blockSizes:null,report:af}}function ev(n,e,t={}){const r=zt("weights",t.weights,Fs)??"first",o=zt("selfLoops",t.selfLoops,["keep","drop"])==="drop";Ja("edgeReducers",t.edgeReducers);const{nodeCount:s,edgeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Uint32Array(i).fill(x);for(let y=0;y<s;y++){const b=a[y+1];let v=a[y];for(;v<b;){const A=c[v],E=hf(c,v,b);if((n.directed||A>=y)&&!(A===y&&o)){const I=l[v];for(let k=v;k<E;k++)u[l[k]]=I}v=E}}const d=Js(u),{src:f,dst:h}=ts(e,d,null),g=ns(e.weights,d,r),w=Jo({directed:n.directed,nodeCount:s,edgeCount:d.count,src:f,dst:h,weights:g}),p=ei(n,d,t.edgeReducers,null);return{parts:Zo(n,w,{directed:n.directed,nodeCount:s,edgeCount:d.count,ids:n.ids,nodes:n.nodes,edges:p,extensions:es(n,null,d.remap)}),nodeOrigin:null,edgeOrigin:d.origin,nodeRemap:null,edgeRemap:d.remap,blockSizes:null,report:{droppedEdges:d.dropped,mergedEdges:d.merged}}}function Je(n,e){const t=n.length,r=e??new Uint32Array(t);if(r.length!==t)throw new P("E_COLUMN_LENGTH",`out has ${r.length} entries, expected ${t}`,{expected:t,found:r.length});let o=0;for(let i=0;i<t;i++){const a=n[i];if(a===x)throw new P("E_PARTITION",`labels[${i}] is INVALID_INDEX`,{index:i});a>o&&(o=a)}const s=o<4*t+1024?tv(n,r,o):nv(n,r);return{labels:r,count:s}}function tv(n,e,t){const r=new Uint32Array(t+1).fill(x);let o=0;for(let s=0;s<n.length;s++){const i=n[s];let a=r[i];a===x&&(a=o++,r[i]=a),e[s]=a}return o}function nv(n,e){const t=new Map;let r=0;for(let o=0;o<n.length;o++){const s=n[o];let i=t.get(s);i===void 0&&(i=r++,t.set(s,i)),e[o]=i}return r}function rv(n,e){if(n.length!==e)throw new P("E_PARTITION",`partition has ${n.length} entries, expected nodeCount ${e}`,{expected:e,found:n.length});let t=-1;for(let r=0;r<e;r++){const o=n[r];if(o===x)throw new P("E_PARTITION",`partition[${r}] is INVALID_INDEX`,{index:r});o>t&&(t=o)}if(t<e){const r=new Uint8Array(t+1);let o=0;for(let s=0;s<e;s++)r[n[s]]===0&&(r[n[s]]=1,o++);if(o===t+1)return{labels:n.slice(),count:t+1}}return Je(n)}function ov(n,e,t,r,o){const s=[];if(o!==void 0){const i={count:t,remap:e,origin:r};for(const a of n.nodes){const c=o[a.meta.name];if(c===void 0)continue;const l=Za(a,i,c);l!==null&&s.push(l)}}return new wn({domain:"node",rowCount:t,columns:s})}function sv(n,e,t){const r=n.length,o=[];for(let u=0;u<r;u++)n[u]!==x&&o.push(u);const s=new Uint32Array(t+1);for(const u of o)s[e[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const i=new Uint32Array(o.length);for(const u of o)i[s[e[u]]++]=u;s.fill(0);for(const u of o)s[n[u]+1]++;for(let u=0;u<t;u++)s[u+1]+=s[u];const a=new Uint32Array(o.length);for(let u=0;u<i.length;u++){const d=i[u];a[s[n[d]]++]=d}const c=new Uint32Array(r).fill(x);let l=0;for(;l<a.length;){const u=a[l];let d=l+1;for(;d<a.length&&n[a[d]]===n[u]&&e[a[d]]===e[u];)d++;for(let f=l;f<d;f++)c[a[f]]=u;l=d}return c}function iv(n,e,t,r={}){const o=zt("weights",r.weights,Fs)??"sum",s=zt("selfLoops",r.selfLoops,["keep","drop"])==="drop",i=(zt("parallel",r.parallel,["merge","keep"])??"merge")==="merge";Ja("nodeReducers",r.nodeReducers),Ja("edgeReducers",r.edgeReducers);const{nodeCount:a,edgeCount:c}=n,{labels:l,count:u}=rv(t,a),d=new Uint32Array(u),f=new Uint32Array(u).fill(x);for(let N=0;N<a;N++){const C=l[N];d[C]++,f[C]===x&&(f[C]=N)}const h=new Uint32Array(c),g=new Uint32Array(c);for(let N=0;N<c;N++){const C=l[e.src[N]],O=l[e.dst[N]];C===O&&s?(h[N]=x,g[N]=x):n.directed||C<=O?(h[N]=C,g[N]=O):(h[N]=O,g[N]=C)}let w;if(i)w=sv(h,g,u);else{w=new Uint32Array(c);for(let N=0;N<c;N++)w[N]=h[N]===x?x:N}const p=Js(w),{src:m,dst:y}=ts(e,p,l),b=ns(e.weights,p,o),v=Jo({directed:n.directed,nodeCount:u,edgeCount:p.count,src:m,dst:y,weights:b}),A=ov(n,l,u,f,r.nodeReducers),E=[];if(r.edgeReducers!==void 0)for(const N of n.edges){const C=r.edgeReducers[N.meta.name];if(C===void 0)continue;const O=Za(N,p,C);O!==null&&E.push(O)}const I=new wn({domain:"edge",rowCount:p.count,columns:E});return{parts:Zo(n,v,{directed:n.directed,nodeCount:u,edgeCount:p.count,ids:nd(u),nodes:A,edges:I,extensions:es(n,l,p.remap)}),nodeOrigin:f,edgeOrigin:p.origin,nodeRemap:l,edgeRemap:p.remap,blockSizes:d,report:{droppedEdges:p.dropped,mergedEdges:p.merged}}}function av(n,e,t,r,o){return{label:n.label,serial:n.serial,directed:n.directed,nodeCount:n.nodeCount,edgeCount:n.edgeCount,arcCount:n.arcCount,selfLoopCount:n.selfLoopCount,rowPtr:n.rowPtr,colIdx:n.colIdx,weights:n.weights,arcToEdge:r,edgeToArc:o,flags:n.flags,ids:n.ids,nodes:ld(n.nodes,e??{}),edges:ld(n.edges,t??{}),graph:n.graph.clone(),extensions:n.extensions,meta:n.meta,arena:n.arena,checksum:!1}}const cv=2166136261,lv=16777619,uv=3421674724,dv=1540483477;class ec{constructor(){this.laneA=cv,this.laneB=uv}word(e){const t=e>>>0;this.laneA=Math.imul(this.laneA^t,lv)>>>0;const r=(t<<16|t>>>16)>>>0;return this.laneB=Math.imul(this.laneB^r,dv)>>>0,this}words(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e[t]);return this}identity(e){this.word(e);for(let t=0;t<e;t++)this.word(t);return this}bytes(e){const{byteLength:t,byteOffset:r}=e;if(this.word(t),r%4===0&&t%4===0){const i=new Uint32Array(e.buffer,r,t/4);for(let a=0;a<i.length;a++)this.word(i[a]);return this}const o=new Uint8Array(e.buffer,r,t);let s=0;for(;s+4<=t;s+=4)this.word(o[s]|o[s+1]<<8|o[s+2]<<16|o[s+3]<<24);if(s<t){let i=0;for(let a=0;s+a<t;a++)i|=o[s+a]<<8*a;this.word(i)}return this}text(e){this.word(e.length);for(let t=0;t<e.length;t++)this.word(e.charCodeAt(t));return this}digest(){return this.laneA.toString(16).padStart(8,"0")+this.laneB.toString(16).padStart(8,"0")}}function mn(n){return new ec().bytes(n).digest()}function gf(n,e){n.text(e.dtype).word(e.length).word(e.nullCount),e.validity!==null?n.words(e.validity):n.word(0);const{dtype:t}=e;switch(t){case"f32":case"f64":case"i32":case"u32":case"u8":case"bool":n.bytes(e.data);break;case"dict":n.words(e.codes).word(e.dictionary.length);for(const r of e.dictionary)n.text(r);break;case"string":n.words(e.offsets).bytes(e.utf8);break;case"list":n.words(e.offsets),gf(n,e.child);break;case"json":n.text(JSON.stringify(e.values));break;default:K0(t)}}function wf(n){if(ka(n))throw new P("E_DETACHED",`column "${n.meta.name}" was transferred away`,{column:n.meta.name});const e=new ec;return gf(e,n),e.digest()}function fv(n){const e=new ec;return e.word(n.directed?1:0).word(n.nodeCount).word(n.edgeCount).word(n.arcCount).word(n.selfLoopCount),e.words(n.rowPtr).words(n.colIdx),n.weights===null?e.word(0):e.bytes(n.weights),n.flags.arcToEdgeIsIdentity?e.identity(n.arcCount).identity(n.edgeCount):e.words(n.arcToEdge).words(n.edgeToArc),e.digest()}let hv=1;const ti=["reverse","coo","edgeList","outDegree","inDegree","degree","weightedOutDegree","weightedInDegree","weightedDegree","selfLoopWeight","totalWeight","selfLoopArcs","selfLoopsPerNode","mate","degreeOrder","reverseDegreeOrder","symmetric"],gv="__graphtyNoStructuredClone";function wv(){}const tc=new WeakMap;function pv(){return{reverse:null,coo:null,edgeList:null,outDegree:null,inDegree:null,degree:null,weightedOutDegree:null,weightedInDegree:null,weightedDegree:null,selfLoopWeight:null,totalWeight:null,selfLoopArcs:null,selfLoopsPerNode:null,mate:null,degreeOrder:null,reverseDegreeOrder:null,symmetric:null}}function On(n,e,t){return new P("E_INVALID_SNAPSHOT",`invariant ${n} violated: ${e}`,{invariant:n,...t})}function mv(n){const{nodeCount:e,edgeCount:t,arcCount:r,flags:o}=n;if(n.rowPtr.length!==e+1)throw On("I1",`rowPtr has ${n.rowPtr.length} entries, expected ${e+1}`,{expected:e+1,found:n.rowPtr.length});if(n.colIdx.length!==r)throw On("I1",`colIdx has ${n.colIdx.length} entries, expected ${r}`,{expected:r,found:n.colIdx.length});if(n.weights!==null&&n.weights.length!==r)throw On("I8",`weights has ${n.weights.length} entries, expected ${r}`,{expected:r,found:n.weights.length});const s=o.arcToEdgeIsIdentity;if(n.arcToEdge===null!==s||n.edgeToArc===null!==s)throw On("I9","arcToEdge / edgeToArc must be null exactly when flags.arcToEdgeIsIdentity",{flag:"arcToEdgeIsIdentity",found:s});if(s&&(!n.directed||r!==t))throw On("I9","flags.arcToEdgeIsIdentity requires a directed snapshot with arcCount === edgeCount",{flag:"arcToEdgeIsIdentity",directed:n.directed,arcCount:r,edgeCount:t});if(n.arcToEdge!==null&&n.arcToEdge.length!==r)throw On("I5",`arcToEdge has ${n.arcToEdge.length} entries, expected ${r}`,{expected:r,found:n.arcToEdge.length});if(n.edgeToArc!==null&&n.edgeToArc.length!==t)throw On("I5",`edgeToArc has ${n.edgeToArc.length} entries, expected ${t}`,{expected:t,found:n.edgeToArc.length});if(n.ids.size!==e)throw On("I11",`ids.size is ${n.ids.size}, expected ${e}`,{expected:e,found:n.ids.size});if(n.nodes.rowCount!==e||n.edges.rowCount!==t||n.graph.rowCount!==1)throw On("I12","table row counts do not match nodeCount / edgeCount / 1",{nodes:n.nodes.rowCount,edges:n.edges.rowCount,graph:n.graph.rowCount})}function ni(n,e){for(const t of e)t.meta.mutable||n.columns.set(t,wf(t))}let yv=class yu{constructor(e){mv(e),this[Au]=!0,this.serial=e.serial??hv++,this.label=e.label,this.formatVersion=Mr,this.directed=e.directed,this.nodeCount=e.nodeCount,this.edgeCount=e.edgeCount,this.arcCount=e.arcCount,this.selfLoopCount=e.selfLoopCount,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.weights=e.weights,this.flags=Object.freeze({...e.flags}),this.ids=e.ids,this.nodes=e.nodes,this.edges=e.edges,this.graph=e.graph,this.extensions=e.extensions,this.meta=e.meta,this.arena=e.arena;let t=null;if(e.checksum){t={core:new Map,columns:new WeakMap,views:new Map},t.core.set("rowPtr",mn(e.rowPtr)),t.core.set("colIdx",mn(e.colIdx)),e.weights!==null&&t.core.set("weights",mn(e.weights)),e.arcToEdge!==null&&t.core.set("arcToEdge",mn(e.arcToEdge)),e.edgeToArc!==null&&t.core.set("edgeToArc",mn(e.edgeToArc)),ni(t,e.nodes),ni(t,e.edges),ni(t,e.graph);for(const o of e.extensions.values())ni(t,o)}const r={arcToEdge:e.arcToEdge,edgeToArc:e.edgeToArc,views:pv(),checksums:t,contentHash:null,edgeIds:null};Object.defineProperty(this,"state",{value:r,enumerable:!1,writable:!1,configurable:!1}),tc.set(this,r),bv(e),Object.defineProperty(this,gv,{value:wv,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get detached(){return this.rowPtr.length===0}get arcToEdge(){this.assertAttached();const{state:e}=this;return e.arcToEdge===null&&(e.arcToEdge=Ba(this.arcCount),e.checksums?.core.set("arcToEdge",mn(e.arcToEdge))),e.arcToEdge}get edgeToArc(){this.assertAttached();const{state:e}=this;return e.edgeToArc===null&&(e.edgeToArc=Ba(this.edgeCount),e.checksums?.core.set("edgeToArc",mn(e.edgeToArc))),e.edgeToArc}outArcs(e){return this.assertAttached(),[this.rowPtr[e],this.rowPtr[e+1]]}outDegreeOf(e){return this.assertAttached(),this.rowPtr[e+1]-this.rowPtr[e]}findArc(e,t){return this.assertAttached(),yb(this.rowPtr,this.colIdx,e,t)}hasArc(e,t){return this.findArc(e,t)!==x}arcsBetween(e,t){return this.assertAttached(),qs(this.rowPtr,this.colIdx,e,t)}multiplicity(e,t){return this.assertAttached(),gd(this.rowPtr,this.colIdx,e,t)}arcSource(e){this.assertAttached();const{coo:t}=this.state.views;return t!==null?t.src[e]:bb(this.rowPtr,e)}edgeSource(e){this.assertAttached();const t=this.state.views.edgeList;return t!==null?t.src[e]:this.arcSource(this.edgeToArc[e])}edgeTarget(e){return this.colIdx[this.edgeToArc[e]]}edgeIndexOf(e){const{state:t}=this,r=ib(this.edges);if(t.edgeIds?.version!==r){const o=this.edges.byRole("id");t.edgeIds={version:r,column:o,index:o===null?null:new fb(o)}}return t.edgeIds.index===null?x:t.edgeIds.index.indexOf(e)}reverse(){return this.cached("reverse",()=>Eb(this))}coo(){return this.cached("coo",()=>_b(this))}edgeList(){return this.cached("edgeList",()=>bd(this))}outDegree(){return this.cached("outDegree",()=>Ar(this.rowPtr,this.nodeCount))}inDegree(){return this.cached("inDegree",()=>this.directed?Ar(this.reverse().rowPtr,this.nodeCount):this.outDegree())}degree(){return this.cached("degree",()=>Ib(this.outDegree(),this.directed?this.inDegree():this.selfLoopsPerNode()))}weightedOutDegree(){return this.cached("weightedOutDegree",()=>this.weights===null?Ga(this.outDegree()):vd(this.rowPtr,this.weights,this.nodeCount))}weightedInDegree(){return this.cached("weightedInDegree",()=>{if(!this.directed)return this.weightedOutDegree();const e=this.reverse();return e.weights===null?Ga(this.inDegree()):vd(e.rowPtr,e.weights,this.nodeCount)})}weightedDegree(){return this.cached("weightedDegree",()=>kb(this.weightedOutDegree(),this.directed?this.weightedInDegree():this.selfLoopWeight()))}selfLoopWeight(){return this.cached("selfLoopWeight",()=>xb(this,{selfLoopArcs:this.selfLoopArcs(),selfLoopsPerNode:this.selfLoopsPerNode()}))}totalWeight(){return this.cached("totalWeight",()=>Sb(this))}selfLoopArcs(){return this.cached("selfLoopArcs",()=>this.materialiseSelfLoops().selfLoopArcs)}selfLoopsPerNode(){return this.cached("selfLoopsPerNode",()=>this.materialiseSelfLoops().selfLoopsPerNode)}selfLoopsAt(e){return this.assertAttached(),vb(this.rowPtr,this.colIdx,e)}mate(){return this.cached("mate",()=>Nb(this))}degreeOrder(e){if((zt("of",e?.of,["forward","reverse"])??"forward")==="reverse"&&this.directed)return this.cached("reverseDegreeOrder",()=>Ad(this.reverse().rowPtr,this.nodeCount));const r=this.cached("degreeOrder",()=>Ad(this.rowPtr,this.nodeCount));return this.directed||(this.state.views.reverseDegreeOrder=r),r}isSymmetric(){return this.cached("symmetric",()=>this.directed?Tb(this,this.reverse()):!0)}prepare(e){for(const t of e)this.materialiseView(t);return this}dropCaches(){const{state:e}=this;for(const t of ti)e.views[t]=null;e.checksums?.views.clear(),this.flags.arcToEdgeIsIdentity&&(e.arcToEdge=null,e.edgeToArc=null,e.checksums?.core.delete("arcToEdge"),e.checksums?.core.delete("edgeToArc"));for(const t of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const r of t)wy(r)}cachedViews(){if(this.detached)return this.dropCaches(),[];const{views:e}=this.state;return ti.filter(t=>e[t]!==null)}toUndirected(e){return this.assertAttached(),this.directed?this.wrapDerived(J2(this,this.edgeEndpoints(),e)):this.wrapDerived(cf())}transpose(){return this.assertAttached(),this.directed?this.wrapDerived(Z2(this,this.reverse())):this.wrapDerived(cf())}simplified(e){return this.assertAttached(),this.wrapDerived(ev(this,this.edgeEndpoints(),e))}withoutSelfLoops(){return this.assertAttached(),this.wrapDerived(H2(this,this.edgeEndpoints()))}filterEdges(e){return this.assertAttached(),this.wrapDerived(q2(this,this.edgeEndpoints(),e))}inducedSubgraph(e){return this.assertAttached(),this.wrapDerived(Y2(this,this.edgeEndpoints(),e))}contract(e,t){return this.assertAttached(),this.wrapDerived(iv(this,this.edgeEndpoints(),e,t))}relabel(e){return this.assertAttached(),this.wrapDerived(X2(this,this.edgeEndpoints(),e))}seal(){Vs(this.nodes),Vs(this.edges),Vs(this.graph);for(const e of this.extensions.values())Vs(e)}withColumns(e,t){this.assertAttached();const r=this.flags.arcToEdgeIsIdentity,o=av(this,e,t,r?null:this.arcToEdge,r?null:this.edgeToArc);return new yu({...o,checksum:this.state.checksums!==null})}byteLength(e={}){let t=this.rowPtr.byteLength+this.colIdx.byteLength;return this.weights!==null&&(t+=this.weights.byteLength),this.flags.arcToEdgeIsIdentity||(t+=this.arcToEdge.byteLength+this.edgeToArc.byteLength),e.views===!0&&(t+=Av(this,this.state.views)),e.columns===!0&&(t+=Ev(this)),e.ids===!0&&(t+=this.ids.byteLength()),t}contentHash(){this.assertAttached();const{state:e}=this;return e.contentHash??=fv(this),e.contentHash}transferables(){return this.assertAttached(),T1(this)}toWire(e){return this.assertAttached(),N1(this,e)}toBytes(e){return this.assertAttached(),d2(this,e)}toByteChunks(e){return this.assertAttached(),h2(this,e)}validate(e={}){this.assertAttached();const t=zt("level",e.level,["structure","full"])??"full";if(typeof e.checksum!="boolean"&&e.checksum!==void 0)throw new P("E_UNSUPPORTED","validate option checksum must be a boolean",{field:"checksum",found:e.checksum,reason:"unsupported option"});if(xy(this.ids))throw new P("E_DETACHED","the id map's storage was transferred away",{serial:this.serial});for(const r of[this.nodes,this.edges,this.graph,...this.extensions.values()])for(const o of r)if(ka(o))throw new P("E_DETACHED",`column "${o.meta.name}" was transferred away`,{column:o.meta.name,serial:this.serial});e.checksum===!0&&this.verifyChecksums(),t==="structure"?Nd(this):r1(this)}assertAttached(){if(this.rowPtr.length===0)throw new P("E_DETACHED","the snapshot's core buffer was transferred away",{serial:this.serial})}cached(e,t){this.assertAttached();const{views:r}=this.state,o=r[e];if(o!==null)return o;const s=t();return r[e]=s,this.recordView(e,s),s}materialiseSelfLoops(){const e=Pb(this),{views:t}=this.state;return t.selfLoopArcs===null&&(t.selfLoopArcs=e.selfLoopArcs,this.recordView("selfLoopArcs",e.selfLoopArcs)),t.selfLoopsPerNode===null&&(t.selfLoopsPerNode=e.selfLoopsPerNode,this.recordView("selfLoopsPerNode",e.selfLoopsPerNode)),{selfLoopArcs:t.selfLoopArcs,selfLoopsPerNode:t.selfLoopsPerNode}}recordView(e,t){mf(this,this.state,e,t)}verifyChecksums(){const e=this.state.checksums;if(e===null)throw new P("E_INVALID_SNAPSHOT","no checksums were recorded for this snapshot",{reason:"no-checksum"});const t=(i,a)=>new P("E_INVALID_SNAPSHOT",`checksum mismatch: ${i} was modified after freeze`,{reason:"checksum",...a}),{state:r}=this,o=[["rowPtr",this.rowPtr],["colIdx",this.colIdx],["weights",this.weights],["arcToEdge",r.arcToEdge],["edgeToArc",r.edgeToArc]];for(const[i,a]of o){const c=e.core.get(i);if(c!==void 0&&a!==null&&mn(a)!==c)throw t(`core array ${i}`,{array:i})}const s=[["nodes",this.nodes],["edges",this.edges],["graph",this.graph],...[...this.extensions].map(([i,a])=>[`extensions[${i}]`,a])];for(const[i,a]of s)for(const c of a){const l=e.columns.get(c);if(l!==void 0&&wf(c)!==l)throw t(`column "${c.meta.name}" of ${i}`,{table:i,column:c.meta.name})}for(const i of ti){const a=r.views[i];if(a!==null)for(const[c,l]of Object.entries(Wa(this,i,a))){const u=e.views.get(`${i}.${c}`);if(u!==void 0&&mn(l)!==u)throw t(`view ${i}.${c}`,{view:i,member:c})}}}edgeEndpoints(){return this.state.views.edgeList??bd(this)}wrapDerived(e){return{snapshot:e.parts===null?this:new yu({...e.parts,checksum:this.state.checksums!==null}),nodeOrigin:e.nodeOrigin,edgeOrigin:e.edgeOrigin,nodeRemap:e.nodeRemap,edgeRemap:e.edgeRemap,blockSizes:e.blockSizes,report:e.report}}materialiseView(e){switch(e){case"reverse":this.reverse();break;case"coo":this.coo();break;case"edgeList":this.edgeList();break;case"outDegree":this.outDegree();break;case"inDegree":this.inDegree();break;case"degree":this.degree();break;case"weightedOutDegree":this.weightedOutDegree();break;case"weightedInDegree":this.weightedInDegree();break;case"weightedDegree":this.weightedDegree();break;case"selfLoopWeight":this.selfLoopWeight();break;case"totalWeight":this.totalWeight();break;case"selfLoopArcs":this.selfLoopArcs();break;case"selfLoopsPerNode":this.selfLoopsPerNode();break;case"mate":this.mate();break;case"degreeOrder":this.degreeOrder();break;case"reverseDegreeOrder":this.degreeOrder({of:"reverse"});break;case"symmetric":this.isSymmetric();break;default:{const t=e;throw new P("E_UNSUPPORTED",`unknown view ${String(t)}`,{view:t})}}}};function bv(n){const e=new Set([n.rowPtr.buffer,n.colIdx.buffer]);n.weights!==null&&e.add(n.weights.buffer),n.arcToEdge!==null&&e.add(n.arcToEdge.buffer),n.edgeToArc!==null&&e.add(n.edgeToArc.buffer);for(const t of Oy(n.ids))e.add(t);for(const t of e)it(t);it(n.ids),it(n.nodes),it(n.edges),it(n.graph);for(const t of n.extensions.values())it(t)}function pf(n){return new yv(n)}function vv(n){if(typeof n!="object"||n===null)return!1;const e=n;return e[Au]===!0&&e.formatVersion===Mr}function Av(n,e){let t=0;for(const r of ti){const o=e[r];o!==null&&!(r==="reverseDegreeOrder"&&o===e.degreeOrder)&&(t+=Rb(n,r,o))}return t}function Ev(n){let e=0;for(const t of[n.nodes,n.edges,n.graph,...n.extensions.values()])for(const r of t)e+=r.byteLength;return e}function mf(n,e,t,r){const o=e.checksums;if(o!==null)for(const[s,i]of Object.entries(Wa(n,t,r)))o.views.set(`${t}.${s}`,mn(i))}function Yr(n,e,t){const r=tc.get(n);return r?.views[e]!==null?!1:(r.views[e]=t,mf(n,r,e,t),!0)}function _v(n,e){const t=tc.get(n);return t===void 0?null:t.views[e]}const Iv=new Set(["keep","error","first","last","sum","min","max"]);function yf(n,e,t){if(typeof e!="string"||!Iv.has(e))throw t(n,e);return e}const kv="graphty.weight";function nc(){return performance.now()}function Sv(n){if(n.selfLoopCount===0)return;const e=n.edgeBound;for(let t=0;t<e;t++)if(n.edgeAlive.get(t)&&n.src.get(t)===n.dst.get(t)){const r=n.src.get(t);throw new P("E_SELF_LOOP",`edge ${t} is a self-loop at node ${r}`,{edge:t,node:r})}}function Pv(n){const e=n.edgeAlive.view().slice(),t=n.src.view(),r=n.dst.view(),o=n.edgeBound;for(let s=0;s<o;s++)t[s]===r[s]&&Le(e,s)&&Kt(e,s);return e}function bf(n,e){const t=n.edgeBound;return{directed:e,nodeCount:n.nodeBound,edgeCount:t,src:n.src.view(),dst:n.dst.view(),weights:n.weight===null?null:n.weight.view()}}function xv(n,e,t,r,o,s){const{rowPtr:i,colIdx:a,arcToEdge:c}=n.core,l=e.nodeBound,u=e.edgeBound,d={staging:e,weights:e.weight===null?null:e.weight.view(),policy:r,countMultiplicity:o,builderIndex:s},f=new Uint32Array(u);for(let w=0;w<u;w++)f[w]=w;const h={survivorOf:f,reduced:null,stored:null,explicit:null,merged:0},g=[];for(let w=0;w<l;w++){const p=i[w+1];let m=i[w];for(;m<p;){const y=a[m],b=Cv(a,m,p);b-m>1&&(t||y>=w)&&(Nv(g,c,m,b),Tv(d,h,w,y,g)),m=b}}return h.merged===0?null:{...h}}function Cv(n,e,t){const r=n[e];let o=e+1;for(;o<t&&n[o]===r;)o++;return o}function Nv(n,e,t,r){n.length=0;for(let o=t;o<r;o++)n.push(e===null?o:e[o])}function Tv(n,e,t,r,o){const{policy:s,staging:i,builderIndex:a}=n;if(s==="error"){const f=[a(o[0]),a(o[1])];throw new P("E_DUPLICATE_EDGE",`edges ${f[0]} and ${f[1]} both connect ${t} -> ${r}`,{source:t,target:r,edges:f})}const c=s==="last"?o[o.length-1]:o[0],l=Ov(n,t,r,o),u=e.survivorOf.length;l!==null&&(e.reduced??=new Float64Array(u),e.stored??=new Uint32Array(Fe(u)),e.reduced[c]=l,Ht(e.stored,c)),(l!==null||o.some(f=>i.weightExplicit(f)))&&!i.weightExplicit(c)&&(e.explicit??=new Uint32Array(Fe(u)),Ht(e.explicit,c));for(const f of o)f!==c&&(e.survivorOf[f]=c,e.merged++)}function Ov(n,e,t,r){const{policy:o}=n;if(o!=="sum"&&o!=="min"&&o!=="max")return null;const s=$v(n.weights,r,o,n.countMultiplicity);if(s!==null&&Number.isNaN(s)){const i=r.map(n.builderIndex);throw new P("E_INVALID_WEIGHT",`duplicateEdges "${o}" over edges ${i.join(", ")} (${e} -> ${t}) yields NaN`,{source:e,target:t,edges:i,policy:o,reason:"reducer"})}return s}function $v(n,e,t,r){if(n===null)return t==="sum"&&r?e.length:null;let o=n[e[0]];for(let s=1;s<e.length;s++){const i=n[e[s]];switch(t){case"sum":o+=i;break;case"min":o=Math.min(o,i);break;case"max":o=Math.max(o,i);break;default:{const a=t;throw new P("E_UNSUPPORTED",`unknown reducer ${a}`,{policy:a})}}}return o}function Rv(n,e,t){const{weight:r}=n;if(r===null||e===0)return null;const o=r.view(),s=t==="f64"&&Dv(o,e),i=n.weightSet!==null||n.weightMode==="omitted";if(!s&&!i)return null;const a=s?"f64":"f32",c=ht(kv,"edge",{dtype:a,role:"weight",nullable:i}),l=a==="f64"?new Float64Array(e):new Float32Array(e);l.set(o.subarray(0,e));const u=i?Lv(n,e):null;return Tt({...Gr(c,e,u),data:l})}function Dv(n,e){for(let t=0;t<e;t++){const r=n[t];if(Math.fround(r)!==r)return!0}return!1}function Lv(n,e){const t=new Uint32Array(Fe(e));for(let r=0;r<e;r++)n.weightExplicit(r)&&Ht(t,r);return t}function Mv(n,e){return n.ids===null||n.idToIndex===null?nd(e):rd(n.ids,e,{map:n.idToIndex})}function rc(n,e,t,r=[]){const o=t.map(i=>i.toColumn(e)),s=new wn({domain:n,rowCount:e,columns:[...o,...r]});return lb(s),s}function Uv(n){const e=[];for(const[t,r]of n)e.push(xa("graph",1,t,[r.value],r.decl??{}));return new wn({domain:"graph",rowCount:1,columns:e})}function Fv(n,e,t,r){if(e===null&&t===null)return null;const o=new Uint32Array(n);for(let s=0;s<n;s++){let i=e===null?s:e.remap[s];i!==x&&t!==null&&r!==null&&(i=r.remap[t.survivorOf[i]]),o[s]=i}return qr(o)?null:o}function Bv(n){const e=new Uint32Array(n);for(let t=0;t<n;t++)e[t]=t;return{remap:e,origin:e,count:n}}function ri(n,e){return new P("E_UNSUPPORTED",`freeze option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function zv(n){n.duplicateEdges!==void 0&&yf("duplicateEdges",n.duplicateEdges,ri);for(const e of["arena","release","profile","checksum"]){const t=n[e];if(t!==void 0&&typeof t!="boolean")throw ri(e,t)}if(n.label!==void 0&&typeof n.label!="string")throw ri("label",n.label);if(n.prepare!==void 0&&!Array.isArray(n.prepare))throw ri("prepare",n.prepare)}function Gv(n,e){const t=e.profile===!0,r={},o=t?nc():0;let s=o;const i=H=>{if(t){const Y=nc();r[H]=(r[H]??0)+(Y-s),s=Y}},{directed:a}=n,c=n.staging;zv(e);const l=e.arena!==!1,u=e.duplicateEdges??n.options.duplicateEdges,d=n.options.selfLoops,f=c.nodeBound,h=c.edgeBound,g=h-c.liveEdgeCount;d==="error"&&Sv(c);const w=a?c.liveEdgeCount:2*c.liveEdgeCount-c.selfLoopCount;if(w>Te)throw new P("E_TOO_LARGE",`arc count ${w} exceeds MAX_COUNT`,{count:w,max:Te});let p=c,m=null,y=null,b=0;const v=d==="drop"&&c.selfLoopCount>0;if(c.hasTombstones||v){const H=ad(f,c.nodeAlive.view()),Y=ad(h,v?Pv(c):c.edgeAlive.view());b=v?c.selfLoopCount:0,p=cd(c,{nodes:H,edges:Y,edgeValues:null,mergedWeights:null,mergedWeightStored:null,mergedWeightSet:null}),m=H,y=Y}i("compact");const A=p.nodeBound;let E=Ya(bf(p,a),l&&u==="keep");i("sort");let I=null,k=null;if(u!=="keep"){const H=y;if(I=xv(E,p,a,u,n.options.weighted!==!1,Y=>H===null?Y:H.origin[Y]),I!==null){const{survivorOf:Y}=I,ee=eb(Y);let Z=null,J=null;if(I.reduced!==null&&I.stored!==null){Z=new Float64Array(ee.count),J=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.stored,ne)&&(Z[ee.remap[ne]]=I.reduced[ne],Ht(J,ee.remap[ne]))}let ce=null;if(I.explicit!==null){ce=new Uint32Array(Fe(ee.count));for(let ne=0;ne<Y.length;ne++)Y[ne]===ne&&Le(I.explicit,ne)&&Ht(ce,ee.remap[ne])}const de=new Uint32Array(Y.length);for(let ne=0;ne<Y.length;ne++)de[ne]=ee.remap[Y[ne]];p=cd(p,{nodes:Bv(A),edges:ee,edgeValues:de,mergedWeights:Z,mergedWeightStored:J,mergedWeightSet:ce}),k=ee,E=Ya(bf(p,a),l)}else l&&(E={...E,core:mb(E.core)});i("duplicates")}const N=p.edgeBound,{core:C,arcCount:O,selfLoopCount:T,flags:$}=E,L=Rv(p,N,n.options.weightDtype);i("weights");const F=Mv(p,A);i("ids");const M=rc("node",A,p.nodeColumns),R=rc("edge",N,p.edgeColumns,L===null?[]:[L]),D=Uv(n.graphValues),U=new Map;for(const H of p.extensions)U.set(H.name,rc("extension",H.rowCount,H.columns));i("columns");const B={label:e.label??null,serial:null,directed:a,nodeCount:A,edgeCount:N,arcCount:O,selfLoopCount:T,rowPtr:C.rowPtr,colIdx:C.colIdx,weights:C.weights,arcToEdge:C.arcToEdge,edgeToArc:C.edgeToArc,flags:$,ids:F,nodes:M,edges:R,graph:D,extensions:U,meta:n.meta,arena:C.arena,checksum:e.checksum===!0},V=pf(B);e.prepare!==void 0&&e.prepare.length>0&&V.prepare(e.prepare),i("snapshot"),t&&(r.total=nc()-o);const W=m!==null&&!qr(m.remap)?m.remap:null,q=Fv(h,y,I,k),K=I===null?0:I.merged,X=Object.freeze({nodeRemap:W,edgeRemap:q,compacted:W!==null||q!==null,droppedSelfLoops:b,mergedEdges:K,droppedEdges:g+b+K,widened:Object.freeze(n.widened.map(H=>Object.freeze({...H}))),timings:Object.freeze({...r})});return{snapshot:V,report:X,staging:p}}const Wv=new Set(["keep","drop","error"]),Vv=new Set(["f32","f64"]),jv="graphty.directed",qv="graphty.pair";function Kn(n,e){return new P("E_UNSUPPORTED",`builder option ${n} has an unsupported value ${String(e)}`,{field:n,found:e,reason:"unsupported option"})}function Hv(n){if(typeof n!="object"||n===null)throw Kn("options",n);if(typeof n.directed!="boolean")throw Kn("directed",n.directed);const e=n.weighted??"auto";if(e!=="auto"&&typeof e!="boolean")throw Kn("weighted",e);const t=n.weightDtype??"f32";if(!Vv.has(t))throw Kn("weightDtype",t);const r=yf("duplicateEdges",n.duplicateEdges??"keep",Kn),o=n.selfLoops??"keep";if(!Wv.has(o))throw Kn("selfLoops",o);const s=n.addMissingNodes??!0;if(typeof s!="boolean")throw Kn("addMissingNodes",s);const i=a=>{const c=n[a];if(c===void 0)return null;if(!Number.isInteger(c)||c<0)throw Kn(a,c);return c};return{fixed:{weighted:e,weightDtype:t,duplicateEdges:r,selfLoops:o,addMissingNodes:s,expectedNodes:i("expectedNodes"),expectedEdges:i("expectedEdges")},directed:n.directed}}function Kv(n){const e={};for(const t of Object.keys(n)){const r=n[t];r!==void 0&&(e[t]=r)}return e}function vf(n,e){return n.dtype===e.dtype&&n.components===e.components&&n.itemDtype===e.itemDtype&&n.itemComponents===e.itemComponents}class oi{constructor(e){this.locked=!1,this.optionsCache=null,this.nodeNames=null,this.edgeNames=null,this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutations=0,this.dirtyFlag=!0,this.disposed=!1;const t=Hv(e);this.fixed=t.fixed,this.directedValue=t.directed,this.staging=this.freshStaging()}static from(e,t){const r=Kv(t??{}),o=e.edges.byRole("weight"),s=r.weightDtype??(o!==null&&o.dtype==="f64"?"f64":void 0),i=r.weighted??(e.flags.weighted?!0:void 0),a=new oi({directed:e.directed,expectedNodes:e.nodeCount,expectedEdges:e.edgeCount,...r,...s===void 0?{}:{weightDtype:s},...i===void 0?{}:{weighted:i}});return a.addGraph(e,{onDuplicateNode:"error"}),a.setMeta(e.meta),a}get options(){return this.check(),this.optionsCache??=Object.freeze({directed:this.directedValue,...this.fixed}),this.optionsCache}get directed(){return this.check(),this.directedValue}get directedLocked(){return this.check(),this.locked}get nodeCount(){return this.check(),this.staging.liveNodeCount}get edgeCount(){return this.check(),this.staging.liveEdgeCount}get nodeBound(){return this.check(),this.staging.nodeBound}get edgeBound(){return this.check(),this.staging.edgeBound}get mutationCount(){return this.check(),this.mutations}get dirty(){return this.check(),this.dirtyFlag}setDirected(e,t){if(this.check(),e!==this.directedValue){if(this.locked)throw new P("E_DIRECTED","the builder's direction is locked",{reason:"locked",directed:this.directedValue});if(this.staging.liveEdgeCount===0){this.directedValue=e,this.optionsCache=null,this.mutated();return}if(!e)throw new P("E_DIRECTED","a builder with edges cannot become undirected",{reason:"edges present",edgeCount:this.staging.liveEdgeCount});if(t?.expand!==!0)throw new P("E_DIRECTED","an undirected builder with edges becomes directed only with { expand: true }",{reason:"expand required",edgeCount:this.staging.liveEdgeCount});this.expandToDirected()}}lockDirected(){this.check(),this.locked=!0}addNode(e){return this.check(),this.addValidatedNode(jn(e))}addNodes(e,t){this.check();const o=(Array.isArray(e)?e:[...e]).map(i=>jn(i));if(t!==void 0&&t.length<o.length)throw new P("E_COLUMN_LENGTH",`out has ${t.length} entries for ${o.length} ids`,{expected:o.length,found:t.length});const s=t??new Uint32Array(o.length);for(let i=0;i<o.length;i++)s[i]=this.addValidatedNode(o[i]);return s}addAnonymousNodes(e){if(this.check(),!Number.isInteger(e)||e<0)throw new P("E_INDEX_RANGE",`node count ${e} is not a non-negative integer`,{count:e});const{staging:t}=this,r=t.nodeBound;if(this.checkNodeLimit(e),t.idToIndex!==null){for(let o=r;o<r+e;o++)if(t.idToIndex.has(o))throw new P("E_DUPLICATE_ID",`node id ${o} exists; anonymous node ${o} cannot use it`,{id:o,index:t.idToIndex.get(o)})}return t.pushAnonymousNodes(e),e>0&&this.mutated(),r}hasNode(e){return this.check(),this.lookup(e)!==x}indexOf(e){return this.check(),this.lookup(e)}idOf(e){this.check();const{staging:t}=this;if(!this.isLiveNode(e))throw new P("E_INDEX_RANGE",`node index ${e} is out of range or removed`,{index:e,bound:t.nodeBound});return t.ids===null?e:t.ids[e]}removeNode(e){this.check();const t=this.lookup(e);if(t===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e});return this.removeLiveNode(t)}removeNodeByIndex(e){if(this.check(),!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e});return this.removeLiveNode(e)}reserve(e,t){this.check();const r=(i,a)=>{if(a===void 0)return 0;if(!Number.isInteger(a)||a<0||a>Te)throw new P("E_TOO_LARGE",`reserve(${i}) ${a} is not an integer in [0, MAX_COUNT]`,{field:i,count:a,max:Te});return a},o=r("nodes",e),s=r("edges",t);$a(o),this.staging.reserve(o,s)}addEdge(e,t,r){this.check();const o=this.checkWeight(r,void 0),s=this.resolveEndpoint(jn(e)),i=this.resolveEndpoint(jn(t));return this.pushEdge(s,i,o)}addEdgeByIndex(e,t,r){this.check();const o=this.checkWeight(r,void 0);return this.checkLiveNode(e),this.checkLiveNode(t),this.pushEdge(e,t,o)}addEdges(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdges: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});for(let c=0;c<o;c++)this.checkLiveNode(e[c]),this.checkLiveNode(t[c]);let s=null;if(r!==void 0){for(let c=0;c<o;c++)this.checkWeight(r[c],c);s=this.fixed.weighted===!1?null:r}this.checkEdgeLimit(o,this.arcsOf(e,t,o));const{staging:i}=this;i.reserve(0,i.edgeBound+o);const a=i.pushEdges(e,t,s);return o>0&&this.mutated(),a}addEdgesByIds(e,t,r){this.check();const o=e.length;if(t.length!==o||r!==void 0&&r.length!==o)throw new P("E_COLUMN_LENGTH",`addEdgesByIds: src has ${o} entries, dst ${t.length}, weights ${r===void 0?"none":r.length}`,{src:o,dst:t.length,weights:r?.length??null});const s=new Array(o),i=new Array(o),a=new Array(o);for(let l=0;l<o;l++)s[l]=jn(e[l]),i[l]=jn(t[l]),a[l]=this.checkWeight(r===void 0?void 0:r[l],l);if(!this.fixed.addMissingNodes)for(let l=0;l<o;l++)this.requireLive(s[l]),this.requireLive(i[l]);this.checkEdgeLimit(o,this.directedValue?o:2*o);const c=this.staging.edgeBound;for(let l=0;l<o;l++){const u=this.resolveEndpoint(s[l]),d=this.resolveEndpoint(i[l]);this.staging.pushEdge(u,d,a[l])}return o>0&&this.mutated(),c}removeEdge(e){return this.check(),this.isLiveEdge(e)?(this.staging.killEdge(e),this.mutated(),!0):!1}hasEdge(e){return this.check(),this.isLiveEdge(e)}edgeEndpoints(e){return this.check(),this.checkEdge(e),[this.staging.src.get(e),this.staging.dst.get(e)]}edgeWeight(e){this.check(),this.checkEdge(e);const{weight:t}=this.staging;return t===null?1:t.get(e)}setEdgeWeight(e,t){this.check(),this.checkEdge(e);const r=this.checkWeight(t,void 0),{staging:o}=this;r!==void 0&&(o.ensureWeights().set(e,r),o.trackWeight(e,!0)),this.mutated()}outEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.outEdges(e):this.staging.incidentEdges(e)}inEdgesOf(e){return this.check(),this.checkNodeIndex(e),this.directedValue?this.staging.inEdges(e):this.staging.incidentEdges(e)}findEdges(e,t){return this.check(),this.checkNodeIndex(e),this.checkNodeIndex(t),this.staging.edgesBetween(e,t,this.directedValue)}declareNodeColumn(e){return this.check(),this.declare("node",e)}declareEdgeColumn(e){return this.check(),this.declare("edge",e)}nodeColumn(e){return this.check(),this.handleOf(this.staging.nodeColumns,e)}edgeColumn(e){return this.check(),this.handleOf(this.staging.edgeColumns,e)}setNodeValue(e,t,r){this.check(),this.checkNodeIndex(t),this.writeCell("node",e,t,r)}setEdgeValue(e,t,r){this.check(),this.checkEdgeIndex(t),this.writeCell("edge",e,t,r)}widenNodeColumn(e,t){this.check(),this.widenColumn("node",e,t)}widenEdgeColumn(e,t){this.check(),this.widenColumn("edge",e,t)}setNodeColumn(e,t,r){this.check(),this.setBulkColumn("node",this.staging.nodeBound,e,t,r??{})}setEdgeColumn(e,t,r){this.check(),this.setBulkColumn("edge",this.staging.edgeBound,e,t,r??{})}setGraphValue(e,t,r){this.check();const o=r??{};ht(e,"graph",{dtype:"json",...o}),t!==void 0&&Qv(e,t,o),this.graphValues.set(e,{decl:o,value:t}),this.mutated()}setMeta(e){this.check(),this.metaValue=Ky(this.metaValue,e),this.mutated()}addExtensionTable(e,t){this.check();const{staging:r}=this;if(r.extensions.some(s=>s.name===e))throw new P("E_COLUMN_EXISTS",`extension table "${e}" already exists`,{table:e});const o=[];for(const s of t){const i=jr(s.name,"extension",s,!1);if(o.some(a=>a.meta.name===i.meta.name))throw new P("E_COLUMN_EXISTS",`column "${s.name}" is declared twice in "${e}"`,{table:e,column:s.name});Xr(o,i.meta,e),o.push(i)}return r.extensions.push({name:e,columns:o,rowCount:0}),this.mutated(),r.extensions.length-1}addExtensionRow(e,t){this.check();const r=this.extensionOf(e);if(t.length!==r.columns.length)throw new P("E_COLUMN_LENGTH",`extension table "${r.name}" has ${r.columns.length} columns; ${t.length} values given`,{table:r.name,expected:r.columns.length,found:t.length});const o=r.rowCount,s=r.columns.map((i,a)=>{const c=this.checkReference(i.meta,t[a]);return i.checkValue(o,c),c});for(let i=0;i<s.length;i++)r.columns[i].write(o,s[i]);return r.rowCount=o+1,this.mutated(),o}addNodeRecord(e,t){this.check();const r=jn(e),o=Object.keys(t);this.checkCells("node",this.prospectiveNodeIndex(r),o,t);const s=this.addValidatedNode(r);for(const i of o)this.writeCell("node",i,s,t[i]);return s}addEdgeRecord(e,t,r,o){this.check();const s=o===void 0?"weight":o;let i;if(s!==null&&Object.prototype.hasOwnProperty.call(r,s)){const l=r[s];if(l!=null){if(typeof l!="number")throw new P("E_INVALID_WEIGHT",`edge weight "${s}" is not a number`,{key:s,found:typeof l});i=l}}const a=Object.keys(r).filter(l=>l!==s);this.checkWeight(i,void 0),this.checkCells("edge",this.staging.edgeBound,a,r);const c=this.addEdge(e,t,i);for(const l of a)this.writeCell("edge",l,c,r[l]);return c}addGraph(e,t){this.check();const r=t?.onDuplicateNode??"merge";if(r!=="merge"&&r!=="error")throw new P("E_UNSUPPORTED",`addGraph option onDuplicateNode has an unsupported value ${String(r)}`,{field:"onDuplicateNode",found:r,reason:"unsupported option"});if(e.directed!==this.directedValue)throw new P("E_DIRECTED",`a ${e.directed?"directed":"undirected"} snapshot cannot be appended to a ${this.directedValue?"directed":"undirected"} builder`,{reason:"direction mismatch",directed:this.directedValue,found:e.directed});const{staging:o}=this,{nodeCount:s,edgeCount:i}=e,a=o.ids===null&&o.nodeBound===0&&e.ids.kind==="identity"&&e.ids.offset===0,c=new Uint32Array(s);let l=s;if(!a){l=0;for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);if(m===x)l++;else if(r==="error")throw new P("E_DUPLICATE_ID",`node id ${Pn(p)} already exists`,{id:p,index:m})}}this.checkNodeLimit(l);const u=e.edgeList();this.checkEdgeLimit(i,this.arcsOf(u.src,u.dst,i));const d=e.edges.byRole("weight"),f=new Array(i);for(let w=0;w<i;w++){let p;d!==null?p=d.isSet(w)?d.value(w):void 0:u.weights!==null&&(p=u.weights[w]),f[w]=this.checkWeight(p,w)}for(const w of e.nodes)this.checkIncomingColumn("node",w);for(const w of e.edges)w!==d&&this.checkIncomingColumn("edge",w);for(const[w,p]of e.extensions)this.checkIncomingExtension(w,p);if(a){const w=this.addAnonymousNodes(s);for(let p=0;p<s;p++)c[p]=w+p}else for(let w=0;w<s;w++){const p=e.ids.idOf(w),m=this.lookup(p);c[w]=m===x?this.addValidatedNode(p):m}e.flags.weighted&&this.fixed.weighted!==!1&&o.ensureWeights();const h=new Uint32Array(i);for(let w=0;w<i;w++)h[w]=this.pushEdge(c[u.src[w]],c[u.dst[w]],f[w]);const g={node:c,edge:h};for(const w of e.nodes)this.copyColumn("node",w,c,g);for(const w of e.edges)w!==d&&this.copyColumn("edge",w,h,g);for(const w of e.graph)w.isSet(0)&&this.setGraphValue(w.meta.name,w.value(0),Sn(w.meta));for(const[w,p]of e.extensions)this.appendExtension(w,p,g);this.mutated()}freeze(e){return this.freezeWithReport(e).snapshot}freezeWithReport(e){this.check();const t=e??{},r={staging:this.staging,directed:this.directedValue,options:this.options,graphValues:this.graphValues,meta:this.metaValue,widened:this.widenings},o=Gv(r,t);return this.staging=o.staging,this.widenings=[],this.dirtyFlag=!1,t.release===!0&&(this.staging=this.freshStaging()),{snapshot:o.snapshot,report:o.report}}clear(){this.check(),this.staging=this.freshStaging(),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.mutated()}dispose(){this.disposed||(this.staging=new La({weightDtype:this.fixed.weightDtype,weighted:!1,expectedNodes:null,expectedEdges:null,resizable:void 0}),this.graphValues=new Map,this.metaValue=Ta,this.widenings=[],this.disposed=!0)}byteLength(){return this.check(),this.staging.byteLength()}check(){if(this.disposed)throw new P("E_BUILDER_DISPOSED","the builder was disposed",{})}mutated(){this.mutations++,this.dirtyFlag=!0}freshStaging(){return new La({weightDtype:this.fixed.weightDtype,weighted:this.fixed.weighted===!0,expectedNodes:this.fixed.expectedNodes,expectedEdges:this.fixed.expectedEdges,resizable:void 0})}prospectiveNodeIndex(e){const{staging:t}=this;return t.idToIndex===null?typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<t.nodeBound?e:t.nodeBound:t.idToIndex.get(typeof e=="number"&&e===0?0:e)??t.nodeBound}lookup(e){const{staging:t}=this;if(t.idToIndex===null)return typeof e!="number"||!Number.isInteger(e)||e<0||e>=t.nodeBound?x:t.nodeAlive.get(e)?e:x;const r=t.idToIndex.get(typeof e=="number"&&e===0?0:e);return r===void 0||!t.nodeAlive.get(r)?x:r}isLiveNode(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.nodeBound&&t.nodeAlive.get(e)}isLiveEdge(e){const{staging:t}=this;return Number.isInteger(e)&&e>=0&&e<t.edgeBound&&t.edgeAlive.get(e)}checkNodeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.nodeBound)throw new P("E_INDEX_RANGE",`node index ${e} is out of range`,{index:e,bound:this.staging.nodeBound})}checkEdgeIndex(e){if(!Number.isInteger(e)||e<0||e>=this.staging.edgeBound)throw new P("E_INDEX_RANGE",`edge index ${e} is out of range`,{edge:e,bound:this.staging.edgeBound})}checkLiveNode(e){if(!this.isLiveNode(e))throw new P("E_UNKNOWN_NODE",`node index ${e} is out of range or removed`,{index:e})}checkEdge(e){if(!this.isLiveEdge(e))throw new P("E_INDEX_RANGE",`edge index ${e} is out of range or removed`,{edge:e,bound:this.staging.edgeBound})}checkNodeLimit(e){if(this.staging.nodeBound+e>Te)throw new P("E_TOO_LARGE",`node count ${this.staging.nodeBound+e} exceeds MAX_COUNT`,{count:this.staging.nodeBound+e,max:Te})}checkEdgeLimit(e,t){const{staging:r}=this,o=r.edgeBound+e,i=(this.directedValue?r.liveEdgeCount:2*r.liveEdgeCount-r.selfLoopCount)+t;if(o>Te||i>Te)throw new P("E_TOO_LARGE",`edge count ${o} (${i} arcs) exceeds MAX_COUNT`,{count:o,arcs:i,max:Te})}arcsOf(e,t,r){if(this.directedValue)return r;let o=0;for(let s=0;s<r;s++)o+=e[s]===t[s]?1:2;return o}addValidatedNode(e){const{staging:t}=this;t.materialiseIds();const o=t.idToIndex.get(e);if(o!==void 0)return t.nodeAlive.get(o)||(t.nodeAlive.set(o,!0),t.liveNodeCount++,this.mutated()),o;this.checkNodeLimit(1);const s=t.pushNode(typeof e=="string"?Ro(e):e);return this.mutated(),s}resolveEndpoint(e){const t=this.lookup(e);if(t!==x)return t;if(this.fixed.addMissingNodes)return this.addValidatedNode(e);throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}requireLive(e){if(this.lookup(e)===x)throw new P("E_UNKNOWN_NODE",`unknown node id ${Pn(e)}`,{id:e})}removeLiveNode(e){const{staging:t}=this,r=[];for(let o=t.firstOut.get(e);o!==x;o=t.nextOut.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));for(let o=t.firstIn.get(e);o!==x;o=t.nextIn.get(o))t.edgeAlive.get(o)&&(t.killEdge(o),r.push(o));return t.nodeAlive.set(e,!1),t.liveNodeCount--,this.mutated(),Uint32Array.from(r).sort()}checkWeight(e,t){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new P("E_INVALID_WEIGHT",`weight ${String(e)} is not a number`,{weight:e,...t===void 0?{}:{edge:t}});if(this.fixed.weighted===!1){if(e!==1)throw new P("E_INVALID_WEIGHT",`weight ${e} on a builder declared unweighted`,{weight:e,reason:"unweighted builder",...t===void 0?{}:{edge:t}});return}return e}}pushEdge(e,t,r){this.checkEdgeLimit(1,this.directedValue||e===t?1:2);const o=this.staging.pushEdge(e,t,r);return this.mutated(),o}expandToDirected(){const{staging:e}=this,t=e.liveEdgeCount;this.checkEdgeLimit(t,t);const r={name:jv,dtype:"bool",role:"directed"},o={name:qv,dtype:"u32",role:"pair",refersTo:"edge"};this.checkDeclaration("edge",r),this.checkDeclaration("edge",o);const s=this.declare("edge",r),i=this.declare("edge",o),a=e.edgeColumns[s],c=e.edgeColumns[i],l=e.edgeBound;for(let u=0;u<l;u++){if(!e.edgeAlive.get(u))continue;a.write(u,!1);const d=e.src.get(u),f=e.dst.get(u);if(d===f)continue;const g=e.weightExplicit(u)&&e.weight!==null?e.weight.get(u):void 0,w=e.pushEdge(f,d,g);a.write(w,!1),c.write(u,w),c.write(w,u)}this.directedValue=!0,this.optionsCache=null,this.mutated()}columnsOf(e){return e==="node"?this.staging.nodeColumns:this.staging.edgeColumns}handleOf(e,t){const r=this.columnIndex(e,t);return r<0?x:r}columnIndex(e,t){let o=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;if(o?.columns!==e||o.map.size!==e.length){const s=new Map;for(let i=0;i<e.length;i++)s.set(e[i].meta.name,i);o={columns:e,map:s},e===this.staging.nodeColumns?this.nodeNames=o:e===this.staging.edgeColumns&&(this.edgeNames=o)}return o.map.get(t)??-1}pushColumn(e,t){e.push(t);const r=e===this.staging.nodeColumns?this.nodeNames:this.edgeNames;return r!==null&&r.columns===e&&r.map.size===e.length-1&&r.map.set(t.meta.name,e.length-1),e.length-1}declare(e,t){const{meta:r,existing:o}=this.checkDeclaration(e,t);if(o!==x)return o;const s=this.columnsOf(e);return this.mutated(),this.pushColumn(s,new Ws(r,!1))}checkDeclaration(e,t){if(typeof t.name!="string"||t.name.length===0)throw new P("E_COLUMN_TYPE","a column declaration needs a non-empty name",{field:"name",found:t.name});const r=ht(t.name,e,t),o=this.columnsOf(e),s=this.columnIndex(o,r.name);if(s>=0){if(vf(o[s].meta,r))return{meta:r,existing:s};throw new P("E_COLUMN_EXISTS",`${e} column "${r.name}" is already declared as ${o[s].meta.dtype}`,{column:r.name,domain:e,found:o[s].meta.dtype,expected:r.dtype})}return Xr(o,r,e),{meta:r,existing:x}}resolveColumn(e,t,r){const o=this.columnsOf(e);if(typeof t=="number"){if(!Number.isInteger(t)||t<0||t>=o.length)throw new P("E_UNKNOWN_COLUMN",`no ${e} column with handle ${t}`,{domain:e,handle:t});return o[t]}const s=this.columnIndex(o,t);if(s>=0)return o[s];if(r==null)return null;const i=Ra(r),a=jr(t,e,{dtype:i,nullable:!0},!0);return this.pushColumn(o,a),a}checkCells(e,t,r,o){const s=this.columnsOf(e);for(const i of r){const a=o[i],c=this.columnIndex(s,i),l=c<0?void 0:s[c];l!==void 0?l.checkValue(t,this.checkReference(l.meta,a)):a!=null&&(Ra(a),typeof a=="string"?wr(a,{column:i,row:t}):typeof a=="object"&&cn(a,`${i}[${t}]`))}}checkReference(e,t){if(e.refersTo===null||t===void 0||t===null)return t;const r=e.refersTo==="node"?this.staging.nodeBound:this.staging.edgeBound,o=s=>{if(typeof s=="number"&&s!==x&&!(s>=0&&s<r))throw new P("E_INDEX_RANGE",`column "${e.name}" refers to ${String(e.refersTo)} ${s}, which is not below ${r}`,{column:e.name,refersTo:e.refersTo,found:s,bound:r})};if(Array.isArray(t)){for(const s of t)o(s);return t}return o(t),t===x?void 0:t}checkIncomingColumn(e,t){const r=this.columnsOf(e);this.columnIndex(r,t.meta.name)<0&&Xr(r,t.meta,e)}checkIncomingExtension(e,t){const r=this.staging.extensions.find(s=>s.name===e),o=[...t];if(r===void 0){const s=[];for(const i of o){const a={...Sn(i.meta),name:i.meta.name},c=jr(a.name,"extension",a,!1);if(s.some(l=>l.meta.name===c.meta.name))throw new P("E_COLUMN_EXISTS",`column "${a.name}" is declared twice in "${e}"`,{table:e,column:a.name});Xr(s,c.meta,e),s.push(c)}return}for(const s of o)if(!r.columns.some(i=>i.meta.name===s.meta.name))throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${s.meta.name}"`,{table:e,column:s.meta.name})}widenColumn(e,t,r){const o=this.columnsOf(e);let s;if(typeof t=="number")s=Number.isInteger(t)&&t>=0&&t<o.length?o[t]:void 0;else{const c=this.columnIndex(o,t);s=c<0?void 0:o[c]}if(s===void 0)throw new P("E_UNKNOWN_COLUMN",`no ${e} column ${String(t)}`,{domain:e,column:t});const i=s.inferredDtype;if(i===null)throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is declared, not inferred`,{column:s.meta.name,domain:e});if(pr(r)<0)throw new P("E_COLUMN_TYPE",`${r} is not a dtype inference widens to`,{column:s.meta.name,dtype:r});const a=r;if(pr(a)<pr(i))throw new P("E_COLUMN_TYPE",`${e} column "${s.meta.name}" is ${i}; it cannot narrow to ${a}`,{column:s.meta.name,found:i,expected:a});a!==i&&(s.widenTo(a),this.widenings.push({column:s.meta.name,domain:e,from:i,to:a}),this.mutated())}writeCell(e,t,r,o){const s=this.resolveColumn(e,t,o);if(s===null)return;const i=s.write(r,this.checkReference(s.meta,o));i!==null&&this.widenings.push({column:s.meta.name,domain:e,from:i.from,to:i.to}),this.mutated()}setBulkColumn(e,t,r,o,s){const i=Jv(e,t,r,o,s,{node:this.staging.nodeBound,edge:this.staging.edgeBound}),a=this.columnsOf(e),c=this.columnIndex(a,r);Xr(a.filter(l=>l.meta.name!==r),i.meta,e),c>=0?a[c]=i:this.pushColumn(a,i),this.mutated()}extensionOf(e){const{extensions:t}=this.staging;if(!Number.isInteger(e)||e<0||e>=t.length)throw new P("E_INDEX_RANGE",`no extension table with handle ${e}`,{handle:e});return t[e]}copyColumn(e,t,r,o){const s=this.columnsOf(e),{name:i}=t.meta;let a=this.columnIndex(s,i);if(a<0){const u={...Sn(t.meta)};Xr(s,t.meta,e),a=this.pushColumn(s,jr(i,e,u,!1))}else{const u=s[a];if(!vf(u.meta,t.meta)){const d=Xv(Da(u.meta.dtype),Da(t.meta.dtype));if(u.meta.dtype!==d){const f=u.meta.dtype;u.widenTo(d),this.widenings.push({column:i,domain:e,from:f,to:d})}}}const c=s[a],l=Af(t.meta,o);for(let u=0;u<t.length;u++){if(!t.isSet(u))continue;let d=t.value(u);l!==null&&(d=Ef(d,l),d===void 0)||c.write(r[u],d)}}appendExtension(e,t,r){const{staging:o}=this,s=[...t];let i=o.extensions.find(l=>l.name===e);if(i===void 0){const l=s.map(d=>({...Sn(d.meta),name:d.meta.name})),u=this.addExtensionTable(e,l);i=o.extensions[u]}const a=i.columns,c=i.rowCount;for(const l of s){const u=a.find(d=>d.meta.name===l.meta.name);if(u===void 0)throw new P("E_UNKNOWN_COLUMN",`extension table "${e}" has no column "${l.meta.name}"`,{table:e,column:l.meta.name});Yv(u,l,c,Af(l.meta,r))}for(const l of a)l.ensureLength(c+t.rowCount);i.rowCount=c+t.rowCount}}function Yv(n,e,t,r){for(let o=0;o<e.length;o++){if(!e.isSet(o)){n.ensureLength(t+o+1);continue}let s=e.value(o);if(r!==null&&(s=Ef(s,r),s===void 0)){n.ensureLength(t+o+1);continue}n.write(t+o,s)}}function Xr(n,e,t){if(e.role===null)return;const r=n.find(o=>o.meta.name!==e.name&&o.meta.role===e.role);if(r!==void 0)throw new P("E_DUPLICATE_ROLE",`role "${e.role}" is already held by column "${r.meta.name}" in ${t}`,{role:e.role,column:e.name,holder:r.meta.name})}function Xv(n,e){return pr(n)>=pr(e)?n:e}function Af(n,e){switch(n.refersTo){case"node":return e.node;case"edge":return e.edge;default:return null}}function Ef(n,e){if(typeof n=="number")return n<e.length?e[n]:void 0;if(typeof n=="object"&&n!==null){const t=Array.from(n),r=t.filter(o=>o<e.length).map(o=>e[o]);return r.length===0&&t.length>0?void 0:r}throw new P("E_COLUMN_TYPE",`a refersTo cell holds a ${typeof n}, not an index or a list`,{found:typeof n,reason:"refersTo"})}function Qv(n,e,t){jr(n,"graph",t.dtype===void 0?{...t,dtype:Ra(e)}:t,t.dtype===void 0).write(0,e)}function Jv(n,e,t,r,o,s){const i=Zu(r),a=o.dtype??i;if(!(a===i||i==="u32"&&(a==="bool"||a==="dict")))throw new P("E_COLUMN_TYPE",`column "${t}": a ${i} array cannot back a ${a} column`,{column:t,field:"dtype",found:i,expected:a});const l=jr(t,n,{nullable:!1,...o,dtype:a},!1),{components:u}=l.meta;let d;switch(a){case"bool":d=Math.ceil(e/32);break;case"dict":d=e;break;case"f32":case"f64":case"i32":case"u32":case"u8":d=e*u;break;default:throw new P("E_COLUMN_TYPE",`column "${t}": a ${String(a)} column cannot adopt a typed array`,{column:t,field:"dtype"})}if(r.length!==d)throw new P("E_COLUMN_LENGTH",`column "${t}": array length ${r.length}, expected ${d}`,{column:t,expected:d,found:r.length});switch(l.ensureLength(e),a){case"bool":{const f=r;for(let h=0;h<e;h++)l.write(h,(f[h>>>5]>>>(h&31)&1)===1);break}case"dict":{const{dictionary:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no dictionary`,{column:t});for(let h=0;h<e;h++){const g=r[h];if(g>=f.size)throw new P("E_COLUMN_TYPE",`column "${t}": code ${g} at row ${h} is outside the ${f.size} declared options`,{column:t,row:h,code:g});l.write(h,f.values[g])}break}default:{const{typed:f}=l;if(f===null)throw new P("E_COLUMN_TYPE",`column "${t}" has no typed storage`,{column:t});const{refersTo:h}=l.meta,g=h==="node"?s.node:s.edge;for(let w=0;w<r.length;w++){const p=r[w];if(h!==null&&p!==x&&p>=g)throw new P("E_INDEX_RANGE",`column "${t}" refers to ${h} ${p} at row ${w}, which is not below ${g}`,{column:t,row:w,refersTo:h,found:p,bound:g});if(h!==null&&p===x&&l.validity===null)throw new P("E_COLUMN_TYPE",`column "${t}": row ${w} of a non-nullable refersTo column holds INVALID_INDEX`,{column:t,row:w,field:"nullable"});f.set(w,p)}if(l.validity!==null)for(let w=0;w<e;w++)l.validity.set(w,h===null||r[w]!==x);break}}return l}const Zv="id";function eA(n,e){if(e.directed!==void 0&&e.directed!==n)throw new P("E_DIRECTED",`options.directed (${String(e.directed)}) disagrees with the input's directed (${String(n)})`,{reason:"direction mismatch",directed:n,found:e.directed});return{builder:{directed:n,weighted:e.weighted,weightDtype:e.weightDtype,duplicateEdges:e.duplicateEdges,selfLoops:e.selfLoops,addMissingNodes:e.addMissingNodes,expectedNodes:e.expectedNodes,expectedEdges:e.expectedEdges},freeze:{label:e.label,prepare:e.prepare,arena:e.arena,release:e.release,profile:e.profile,checksum:e.checksum}}}function _f(n){return ArrayBuffer.isView(n)}function oc(n,e,t,r,o){const s=_f(o)?o:o.data,i=_f(o)?{}:o.decl;if(ArrayBuffer.isView(s)){e==="node"?n.setNodeColumn(r,s,i):n.setEdgeColumn(r,s,i);return}const a=xa(e,t,r,s,i),c={...Sn(a.meta),name:r,dtype:a.dtype},l=e==="node"?n.declareNodeColumn(c):n.declareEdgeColumn(c);for(let u=0;u<t;u++){if(!a.isSet(u))continue;const d=a.value(u);e==="node"?n.setNodeValue(l,u,d):n.setEdgeValue(l,u,d)}}function si(n,e,t){return new P("E_COLUMN_LENGTH",`${n} has ${t} entries, expected ${e}`,{field:n,expected:e,found:t})}function tA(n){const{nodeCount:e,ids:t}=n;if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new P("E_INDEX_RANGE",`nodeCount ${e} is not a non-negative integer`,{field:"nodeCount",found:e});if(t!==void 0){if(e!==void 0&&e!==t.length)throw si("ids",e,t.length);return t.length}if(e===void 0)throw new P("E_INDEX_RANGE","nodeCount is required when no ids are given",{field:"nodeCount"});return e}function nA(n,e){const t=n.addNodes(e);for(let r=0;r<t.length;r++)if(t[r]!==r){const o=e[r];throw new P("E_DUPLICATE_ID",`ids[${r}] repeats the id of index ${t[r]}`,{id:o,index:t[r],position:r})}}function rA(n){const{src:e,dst:t,weights:r,edgeIds:o}=n;if(t.length!==e.length)throw si("dst",e.length,t.length);if(r!==void 0&&r.length!==e.length)throw si("weights",e.length,r.length);if(o!==void 0&&o.length!==e.length)throw si("edgeIds",e.length,o.length)}function sc(n,e={}){const{src:t,dst:r,weights:o}=n;rA(n);const s=tA(n),i=t.length,a=eA(n.directed,e),c={...a.builder,weightDtype:e.weightDtype??(o instanceof Float64Array?"f64":void 0),expectedNodes:e.expectedNodes??s,expectedEdges:e.expectedEdges??i},l=new oi(c);if(n.ids===void 0?l.addAnonymousNodes(s):nA(l,n.ids),l.addEdges(t,r,o),n.nodeColumns!==void 0)for(const u of Object.keys(n.nodeColumns))oc(l,"node",s,u,n.nodeColumns[u]);if(n.edgeColumns!==void 0)for(const u of Object.keys(n.edgeColumns))oc(l,"edge",i,u,n.edgeColumns[u]);return n.edgeIds!==void 0&&oc(l,"edge",i,Zv,{data:n.edgeIds,decl:{role:"id",unique:!0}}),n.meta!==void 0&&l.setMeta(n.meta),l.freeze(a.freeze)}const at=new DataView(new ArrayBuffer(8));function Qt(n){return at.setFloat64(0,n,!0),at.getInt32(4,!0)}function If(n){return at.setFloat64(0,n,!0),at.getUint32(0,!0)}const Ir=.6931471803691238,kr=19082149292705877e-26,oA=0x40000000000000,sA=.6666666666666735,iA=.3999999999940942,aA=.2857142874366239,cA=.22222198432149784,lA=.1818357216161805,uA=.15313837699209373,dA=.14798198605116586;function Ge(n){let e=n,t=Qt(e);const r=If(e);let o=0;if(t<1048576){if((t&2147483647|r)===0)return-1/0;if(t<0)return Number.NaN;o-=54,e*=oA,t=Qt(e)}if(t>=2146435072)return e+e;o+=(t>>20)-1023,t&=1048575;const s=t+614244&1048576;return at.setFloat64(0,e,!0),at.setInt32(4,t|s^1072693248,!0),e=at.getFloat64(0,!0),o+=s>>20,fA(e-1,o,t)}function fA(n,e,t){if((1048575&2+t)<3){if(n===0)return e===0?0:e*Ir+e*kr;const l=n*n*(.5-.3333333333333333*n);return e===0?n-l:e*Ir-(l-e*kr-n)}const r=n/(2+n),o=r*r,s=o*o,i=s*(iA+s*(cA+s*uA)),c=o*(sA+s*(aA+s*(lA+s*dA)))+i;if((t-398458|440401-t)>0){const l=.5*n*n;return e===0?n-(l-r*(l+c)):e*Ir-(l-(r*(l+c)+e*kr)-n)}return e===0?n-r*(n-c):e*Ir-(r*(n-c)-e*kr-n)}const kf=-.16666666666666632,hA=.00833333333332249,gA=-.0001984126982985795,wA=27557313707070068e-22,pA=-25050760253406863e-24,mA=158969099521155e-24,yA=.0416666666666666,bA=-.001388888888887411,vA=2480158728947673e-20,AA=-27557314351390663e-23,EA=2087572321298175e-24,_A=-11359647557788195e-27;function rs(n,e,t){if((Qt(n)&2147483647)<1044381696&&Math.trunc(n)===0)return n;const r=n*n,o=r*n,s=hA+r*(gA+r*(wA+r*(pA+r*mA)));return t===0?n+o*(kf+r*s):n-(r*(.5*e-o*s)-e-o*kf)}function os(n,e){const t=Qt(n)&2147483647;if(t<1044381696&&Math.trunc(n)===0)return 1;const r=n*n,o=r*(yA+r*(bA+r*(vA+r*(AA+r*(EA+r*_A)))));if(t<1070805811)return 1-(.5*r-(r*o-n*e));let s;t>1072234496?s=.28125:(at.setInt32(4,t-2097152,!0),at.setUint32(0,0,!0),s=at.getFloat64(0,!0));const i=.5*r-s;return 1-s-(i-(r*o-n*e))}const IA=.6366197723675814,Sf=1.5707963267341256,ic=6077100506506192e-26,Pf=6077100506303966e-26,ac=20222662487959506e-37,kA=20222662487111665e-37,SA=84784276603689e-45,Oe=new Float64Array(2);function xf(n){const e=Qt(n),t=e&2147483647;if(t<1073928572){const d=e>0?1:-1;let f=n-d*Sf;return t===1073291771?(f-=d*Pf,Oe[0]=f-d*ac,Oe[1]=f-Oe[0]-d*ac):(Oe[0]=f-d*ic,Oe[1]=f-Oe[0]-d*ic),d}const r=Math.abs(n),o=Math.floor(r*IA+.5);let s=r-o*Sf,i=o*ic;const a=t>>20;let c=s-i,l=a-(Qt(c)>>20&2047);if(l>16){let d=s;i=o*Pf,s=d-i,i=o*ac-(d-s-i),c=s-i,l=a-(Qt(c)>>20&2047),l>49&&(d=s,i=o*kA,s=d-i,i=o*SA-(d-s-i),c=s-i)}const u=s-c-i;return e<0?(Oe[0]=-c,Oe[1]=-u,-o):(Oe[0]=c,Oe[1]=u,o)}const PA=6.283185307179586;function Cf(n,e){return e>1094263291?n%PA:n}function Jt(n){const e=Qt(n)&2147483647;if(e<=1072243195)return rs(n,0,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return rs(Oe[0],Oe[1],1);case 1:return os(Oe[0],Oe[1]);case 2:return-rs(Oe[0],Oe[1],1);default:return-os(Oe[0],Oe[1])}}function yn(n){const e=Qt(n)&2147483647;if(e<=1072243195)return os(n,0);if(e>=2146435072)return Number.NaN;switch(xf(Cf(n,e))&3){case 0:return os(Oe[0],Oe[1]);case 1:return-rs(Oe[0],Oe[1],1);case 2:return-os(Oe[0],Oe[1]);default:return rs(Oe[0],Oe[1],1)}}const Nf=3.141592653589793,Tf=1.5707963267948966,ii=6123233995736766e-32,xA=.16666666666666666,CA=-.3255658186224009,NA=.20121253213486293,TA=-.04005553450067941,OA=.0007915349942898145,$A=3479331075960212e-20,RA=-2.403394911734414,DA=2.0209457602335057,LA=-.6882839716054533,MA=.07703815055590194;function cc(n){const e=n*(xA+n*(CA+n*(NA+n*(TA+n*(OA+n*$A))))),t=1+n*(RA+n*(DA+n*(LA+n*MA)));return e/t}function Of(n){const e=Qt(n),t=e&2147483647;if(t>=1072693248)return(t-1072693248|If(n))===0?e>0?0:Nf+2*ii:Number.NaN;if(t<1071644672)return t<=1012924416?Tf+ii:Tf-(n-(ii-n*cc(n*n)));if(e<0){const c=(1+n)*.5,l=Math.sqrt(c),u=cc(c)*l-ii;return Nf-2*(l+u)}const r=(1-n)*.5,o=Math.sqrt(r);at.setFloat64(0,o,!0),at.setUint32(0,0,!0);const s=at.getFloat64(0,!0),i=(r-s*s)/(o+s),a=cc(r)*o+i;return 2*(s+a)}const UA=709.782712893384,FA=-745.1332191019411,BA=1.4426950408889634,zA=9332636185032189e-317,GA=.16666666666666602,WA=-.0027777777777015593,VA=6613756321437934e-20,jA=-16533902205465252e-22,qA=41381367970572385e-24;function $f(n,e){return at.setFloat64(0,n,!0),at.setInt32(4,at.getInt32(4,!0)+(e<<20),!0),at.getFloat64(0,!0)}function HA(n,e,t){return e>=2146435072?!t||Number.isNaN(n)?n+n:0:n>UA?1/0:n<FA?0:null}const Sr=new Float64Array(3);function KA(n,e,t){if(e<1072734898){Sr[0]=t?-1:1,Sr[1]=t?n+Ir:n-Ir,Sr[2]=t?-kr:kr;return}const r=Math.trunc(BA*n+(t?-.5:.5));Sr[0]=r,Sr[1]=n-r*Ir,Sr[2]=r*kr}function Qr(n){const e=Qt(n),t=e<0,r=e&2147483647,o=r>=1082535490?HA(n,r,t):null;if(o!==null)return o;if(r<1043333120)return 1+n;let s=0,i=0,a=0,c=n;r>1071001154&&(KA(n,r,t),[a,s,i]=Sr,c=s-i);const l=c*c,u=c-l*(GA+l*(WA+l*(VA+l*(jA+l*qA))));if(a===0)return 1-(c*u/(u-2)-c);const d=1-(i-c*u/(2-u)-s);return a>=-1021?$f(d,a):$f(d,a+1e3)*zA}function YA(...n){let e=0,t=!1;for(const s of n){const i=Math.abs(s);Number.isNaN(i)?t=!0:i>e&&(e=i)}if(e===1/0)return 1/0;if(t)return Number.NaN;if(e===0)return 0;let r=0,o=0;for(const s of n){const i=Math.abs(s)/e,a=i*i-o,c=r+a;o=c-r-a,r=c}return Math.sqrt(r)*e}function XA(n,e){let t=n,r=Math.abs(e),o=1;for(;r>0;)r%2===1&&(o*=t),t*=t,r=Math.floor(r/2);return e<0?1/o:o}function QA(n,e){return n===0?e>0?0:1/0:n===1/0?e>0?1/0:0:e===.5?Math.sqrt(n):Qr(e*Ge(n))}function JA(n,e){if(e===0)return 1;if(Number.isNaN(n)||Number.isNaN(e))return Number.NaN;const t=Number.isInteger(e);if(t&&Math.abs(e)<=1024)return XA(n,e);const r=Math.abs(n);if(!Number.isFinite(e))return r===1?Number.NaN:r>1==e>0?1/0:0;if(n<0&&!t&&r!==1/0)return Number.NaN;const o=QA(r,e);return(n<0||Object.is(n,-0))&&t&&e%2!==0?-o:o}function Rf(n){if(n.ids===void 0)throw new P("E_UNKNOWN_NODE","node ids cannot be resolved: this graph has no id map (pass a GraphSnapshot)",{reason:"no id map"});return n.ids}function xe(n,e){return typeof e=="number"?e:Rf(n).requireIndex(e.id)}function ss(n,e){return"mask"in e?(Qs(e.mask,n.nodeCount,"nodes"),sf(e.mask,n.nodeCount)):"ids"in e?Rf(n).indicesOf(e.ids,"throw"):e}function Df(n,e){if("mask"in e)return Qs(e.mask,n.nodeCount,"nodes"),e.mask;const t=ss(n,e),r=At(n.nodeCount);for(let o=0;o<t.length;o++){const s=t[o];if(!Number.isInteger(s)||s<0||s>=n.nodeCount)throw new P("E_INDEX_RANGE",`node index ${String(s)} is out of range for ${n.nodeCount} nodes`,{index:s,nodeCount:n.nodeCount});pn(r,s,!0)}return r}function Q(n,e){return Object.assign(n,{code:e})}function lc(n,e,t,r){const o=t===void 0?`${n}: ${String(e)} nodes need ${String(r)} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`${n}: ${String(e)} nodes exceeds maxNodes ${String(t)}; the result would allocate ${String(r)} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(Q(new RangeError(o),"E_TOO_LARGE"),{params:{nodeCount:e,maxNodes:t??null,bytes:r}})}function Lf(n,e,t,r,o){if(t!==void 0&&(e>t||Number.isNaN(t)))throw lc(n,e,t,r);try{return o()}catch(s){throw s instanceof RangeError?lc(n,e,void 0,r):s}}class Mf extends Error{constructor(e,t,r){super(`${e} did not converge in ${String(t)} iterations (tolerance ${String(r)}); raise maxIterations or tolerance`),this.algorithm=e,this.iterations=t,this.tolerance=r,this.name="ConvergenceError",this.code="E_NOT_CONVERGED"}}class uc extends Error{constructor(e,t,r){super(`cannot walk the shortest path from node ${String(e)} to node ${String(t)}: the predecessor array has a ${r}`),this.source=e,this.target=t,this.reason=r,this.name="PathWalkError",this.code="E_BAD_PATH"}}class ZA extends Error{constructor(e){super(`${e}: the accelerator's shortest-path counts overflowed, so its scores are wrong; run the CPU ${e} instead`),this.algorithm=e,this.name="PathCountOverflowError",this.code="E_PATH_COUNT_OVERFLOW"}}function Uf(n,e){let t=0,r=n.length-1;for(;t<r;){const o=t+r>>1;n[o+1]<=e?t=o+1:r=o}return t}class Yn{constructor(e,t=!1){this.size=0,this.tieBreakByIndex=t,this.heap=new Uint32Array(e),this.slot=new Uint32Array(e).fill(x),this.key=new Float64Array(e)}isEmpty(){return this.size===0}has(e){return this.slot[e]!==x}keyOf(e){return this.key[e]}peekKey(){return this.size===0?1/0:this.key[this.heap[0]]}push(e,t){if(!(e>=0&&e<this.slot.length))throw new RangeError(`Node index ${String(e)} is outside the heap's ${String(this.slot.length)} nodes`);this.key[e]=t,this.heap[this.size]=e,this.slot[e]=this.size,this.size++,this.siftUp(this.size-1)}pushOrDecrease(e,t){const r=this.slot[e];if(r===x){this.push(e,t);return}t<this.key[e]&&(this.key[e]=t,this.siftUp(r))}pop(){const e=this.heap[0];if(this.slot[e]=x,this.size--,this.size>0){const t=this.heap[this.size];this.heap[0]=t,this.slot[t]=0,this.siftDown(0)}return e}before(e,t){const r=this.key[e],o=this.key[t];return r<o||this.tieBreakByIndex&&r===o&&e<t}siftUp(e){let t=e;const r=this.heap[t];for(;t>0;){const o=t-1>>1,s=this.heap[o];if(!this.before(r,s))break;this.heap[t]=s,this.slot[s]=t,t=o}this.heap[t]=r,this.slot[r]=t}siftDown(e){let t=e;const r=this.heap[t];for(;;){const o=2*t+1;if(o>=this.size)break;const s=o+1,i=s<this.size&&this.before(this.heap[s],this.heap[o])?s:o,a=this.heap[i];if(!this.before(a,r))break;this.heap[t]=a,this.slot[a]=t,t=i}this.heap[t]=r,this.slot[r]=t}}function Ff(n,e,t,r){const o=[];let s=r;for(;s!==t;){if(o.length>=n.nodeCount-1)throw new uc(t,r,"cycle");const i=e[s];if(!(i<n.arcCount))throw new uc(t,r,"gap");o.push(i),s=Uf(n.rowPtr,i)}return o}function Jr(n,e,t,r){const o=xe(n,r);if(o===t)return Uint32Array.of(t);if(e[o]===x)return new Uint32Array(0);const s=[o,...Ff(n,e,t,o).map(a=>Uf(n.rowPtr,a))],i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Zr(n,e,t,r){const o=xe(n,r);if(o===t||e[o]===x)return new Uint32Array(0);const s=Ff(n,e,t,o).map(a=>n.arcToEdge[a]),i=new Uint32Array(s.length);for(let a=0;a<s.length;a++)i[a]=s[s.length-1-a];return i}function Bf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=new Float64Array(o).fill(1/0),l=new Uint32Array(o).fill(x),u=new Yn(o),d=t.cutoff??1/0;for(c[r]=0,u.push(r,0);!u.isEmpty();){const f=u.pop(),h=c[f],g=s[f+1];for(let w=s[f];w<g;w++){const p=a===null?1:a[w],m=i[w],y=h+p;y<c[m]&&y<=d&&(c[m]=y,l[m]=w,u.pushOrDecrease(m,y))}}return{dist:c,predArc:l,pathTo:f=>Jr(n,l,r,f),pathEdges:f=>Zr(n,l,r,f)}}const zf=5792;function e3(n,e){if(e.weighted===!1)return{w:null,negative:!1};if(e.weights!==void 0&&e.weights.length!==n.arcCount)throw Q(new RangeError(`allPairsShortestPath: the weights override has ${String(e.weights.length)} entries; the snapshot has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");const t=e.weights??n.weights;if(t===null)return{w:null,negative:!1};let r=!0,o=!1;for(let s=0;s<n.arcCount;s++){const i=t[s];if(!Number.isFinite(i)){const a=e.weights===void 0&&!Number.isNaN(i)?"; a finite weight above the f32 range (3.4e38) becomes Infinity in the snapshot's f32 arc weights -- pass the exact f64 weights through the weights override":"";throw Q(new RangeError(`allPairsShortestPath: arc ${String(s)} has weight ${String(i)}; weights must be finite${a}`),"E_BAD_WEIGHT")}r&&(r=i===1),o||(o=i<0)}return{w:r?null:t,negative:o}}function t3(n,e,t,r,o){const{nodeCount:s,rowPtr:i,colIdx:a}=n;r.fill(1/0);for(let c=0;c<s;c++){const l=c*s;for(let u=i[c];u<i[c+1];u++){const d=a[u],f=e===null?1:e[u];d!==c&&f<r[l+d]&&(r[l+d]=f,o!==null&&(o[l+d]=u))}r[l+c]=0}for(let c=0;c<s;c++){const l=c*s,u=r.subarray(l,l+s);for(let d=0;d<s;d++){const f=d*s,h=r[f+c];if(h===1/0)continue;const g=r.subarray(f,f+s);if(o===null)for(let w=0;w<g.length;w++){const p=h+u[w];p<g[w]&&(g[w]=p)}else{const w=o.subarray(l,l+s),p=o.subarray(f,f+s);for(let m=0;m<g.length;m++){const y=h+u[m];y<g[m]&&(g[m]=y,p[m]=w[m])}}}if(t){for(let d=0;d<s;d++)if(r[d*s+d]<0)return!0}}return!1}function n3(n,e){for(let t=0;t<n.nodeCount;t++)for(let r=n.rowPtr[t];r<n.rowPtr[t+1];r++)if(e[r]<0&&(!n.directed||n.colIdx[r]===t))return!0;return!1}function r3(n,e,t){const{nodeCount:r,rowPtr:o,colIdx:s}=n,i=new Uint32Array(r);e.fill(1/0);for(let a=0;a<r;a++){const c=e.subarray(a*r,a*r+r),l=t?.subarray(a*r,a*r+r);c[a]=0,i[0]=a;let u=1;for(let d=0;d<u;d++){const f=i[d],h=c[f]+1;for(let g=o[f];g<o[f+1];g++){const w=s[g];c[w]===1/0&&(c[w]=h,l!==void 0&&(l[w]=g),i[u++]=w)}}}}function o3(n,e,t,r){const{nodeCount:o,rowPtr:s,colIdx:i}=n,a=new Yn(o);t.fill(1/0);for(let c=0;c<o;c++){const l=t.subarray(c*o,c*o+o),u=r?.subarray(c*o,c*o+o);for(l[c]=0,a.push(c,0);!a.isEmpty();){const d=a.pop(),f=l[d];for(let h=s[d];h<s[d+1];h++){const g=i[h],w=f+e[h];w<l[g]&&(l[g]=w,u!==void 0&&(u[g]=h),a.pushOrDecrease(g,w))}}}}function s3(n,e,t,r){if(r==="floyd-warshall")return"floyd-warshall";if(e===null)return"bfs";if(t){if(r==="per-source")throw Q(new Error('allPairsShortestPath: method "per-source" runs Dijkstra, which is incorrect with a negative weight; use "auto" or "floyd-warshall"'),"E_BAD_OPTION");return"floyd-warshall"}const o=n.nodeCount;return r==="per-source"||3*n.arcCount<o*o?"dijkstra":"floyd-warshall"}function Gf(n,e={}){const t=n.nodeCount,r=e.maxNodes??zf;if(!(t<=r))throw lc("allPairsShortestPath",t,r,(e.paths===!0?12:8)*t*t);const{w:o,negative:s}=e3(n,e),i=s3(n,o,s,e.method),a=new Float64Array(t*t),c=e.paths===!0?new Uint32Array(t*t).fill(x):null;let l=!1;i==="bfs"?r3(n,a,c):i==="dijkstra"&&o!==null?o3(n,o,a,c):l=s&&o!==null&&n3(n,o)||t3(n,o,s,a,c),l&&a.fill(Number.NaN);const u=(d,f)=>{const h=xe(n,d),g=xe(n,f);if(c===null)throw Q(new Error("allPairsShortestPath: pass paths: true to walk shortest paths"),"E_BAD_OPTION");if(l)throw new uc(h,g,"cycle");return c.subarray(h*t,h*t+t)};return{dist:a,n:t,hasNegativeCycle:l,method:i,predArc:c,pathTo:(d,f)=>Jr(n,u(d,f),xe(n,d),f),pathEdges:(d,f)=>Zr(n,u(d,f),xe(n,d),f)}}function Wf(n,e,t={}){const r=xe(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.weights??n.weights,c=t.cutoff??1/0,l=new Float64Array(o).fill(1/0),u=new Uint32Array(o).fill(x);l[r]=0;const d=()=>{let g=!1;for(let w=0;w<o;w++){const p=l[w];if(p===1/0)continue;const m=s[w+1];for(let y=s[w];y<m;y++){const b=i[y],v=p+(a===null?1:a[y]);v<l[b]&&v<=c&&(l[b]=v,u[b]=y,g=!0)}}return g};let f=!1;for(let g=0;g<o-1&&!f;g++)f=!d();const h=!f&&d();return{dist:l,predArc:u,hasNegativeCycle:h,pathTo:g=>Jr(n,u,r,g),pathEdges:g=>Zr(n,u,r,g)}}const i3=2654435769;function a3(n,e){const t=Array.from({length:n},(o,s)=>s);let r=i3;for(let o=0;o<e;o++){r=r+1831565813>>>0;let s=Math.imul(r^r>>>15,r|1);s=s+Math.imul(s^s>>>7,s|61)^s;const i=((s^s>>>14)>>>0)/2**32,a=o+Math.floor(i*(n-o));[t[o],t[a]]=[t[a],t[o]]}return t.slice(0,e)}function is(n,e,t,r="betweenness"){const o=n.nodeCount,s=e===void 0?void 0:Array.from(ss(n,e));if(t!==void 0&&(!Number.isInteger(t)||t<0||t>o))throw Q(new RangeError(`${r}: k must be an integer in [0, ${o}], got ${t}`),"E_BAD_OPTION");if(s!==void 0){for(const i of s)if(!Number.isInteger(i)||i<0||i>=o)throw Q(new RangeError(`${r}: sources must be node indices in [0, ${o}), got ${i}`),"E_BAD_NODE");if(t!==void 0&&t!==s.length)throw Q(new RangeError(`${r}: k (${t}) must be absent or equal sources.length (${s.length})`),"E_BAD_OPTION");return s}return t===void 0?Array.from({length:o},(i,a)=>a):a3(o,t)}function Vf(n,e,t,r,o,s){const{nodeCount:i,rowPtr:a,colIdx:c,arcToEdge:l}=n,u=new Int32Array(i).fill(-1),d=new Float64Array(i),f=new Float64Array(i),h=new Uint32Array(i);for(const g of e){let w=0,p=0;for(u[g]=0,d[g]=1,h[p++]=g;w<p;){const m=h[w++],y=u[m]+1;let b=-1;for(let v=a[m],A=a[m+1];v<A;v++){const E=c[v];E===b||o!==null&&!_e(o,l[v])||(b=E,u[E]<0&&(u[E]=y,h[p++]=E),u[E]===y&&(d[E]+=d[m]))}}for(let m=p-1;m>=0;m--){const y=h[m],b=u[y]+1;let v=-1;for(let A=a[y],E=a[y+1];A<E;A++){const I=c[A];if(!(I===v||o!==null&&!_e(o,l[A]))&&(v=I,u[I]===b)){const k=d[y]/d[I]*(1+f[I]);f[y]+=k,r!==null&&(r[l[A]]+=k)}}t!==null&&y!==g&&(t[y]+=s?f[y]+1:f[y])}t!==null&&s&&(t[g]+=p-1);for(let m=0;m<p;m++){const y=h[m];u[y]=-1,d[y]=0,f[y]=0}}}function jf(n,e,t,r){const o=n.directed?1:2,s=t===!0&&r>0?r:o;for(let i=0;i<e.length;i++)e[i]/=s;return s}function qf(n,e={}){const t=n.nodeCount,r=is(n,e.sources,e.k),o=new Float64Array(t),s=e.endpoints===!0;Vf(n,r,o,null,null,s);const i=jf(n,o,e.normalized,s?t*(t-1):(t-1)*(t-2));return{scores:o,iterations:r.length,converged:!0,divisor:i}}function dc(n,e={}){const t=n.nodeCount,r=e.alive??null;if(r!==null&&r.length<Math.ceil(n.edgeCount/32))throw Q(new RangeError(`edgeBetweennessCentrality: alive covers fewer than ${n.edgeCount} edges`),"E_BAD_OPTION");const o=new Float64Array(n.edgeCount);Vf(n,is(n,e.sources,e.k),null,o,r,!1);const s=jf(n,o,e.normalized,(t-1)*(t-2));return{scores:o,divisor:s}}function fc(n,e,t){return{pathTo:r=>Jr(n,t,e,r),pathEdges:r=>Zr(n,t,e,r)}}function ai(n,e,t="start"){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`${t} node index ${String(r)} is out of range for ${String(n.nodeCount)} nodes`),"E_BAD_NODE");return r}function Hf(n,e){return e===void 0?x:ai(n,e,"target")}function ci(n,e){if(e===void 0)return null;const{rowPtr:t,nodeCount:r}=n;if(e.length!==n.arcCount)throw Q(new RangeError(`arcOrder has ${String(e.length)} entries, expected ${String(n.arcCount)}`),"E_BAD_OPTION");const o=new Uint8Array(e.length);for(let s=0;s<r;s++){const i=t[s],a=t[s+1];for(let c=i;c<a;c++){if(e[c]<i||e[c]>=a)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} is not an arc of node ${String(s)}`),"E_BAD_OPTION");if(o[e[c]]===1)throw Q(new RangeError(`arcOrder[${String(c)}] = ${String(e[c])} repeats an arc of node ${String(s)}`),"E_BAD_OPTION");o[e[c]]=1}}return e}function Kf(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=ci(n,t.arcOrder),c=new Uint32Array(o).fill(x),l=new Uint32Array(o).fill(x),u=new Uint32Array(o).fill(x),d=new Uint32Array(o),f=t.maxDepth??x,h=Hf(n,t.target);let g=0,w=0;for(d[w++]=r,u[r]=0;g<w;){const p=d[g++];if(p===h)break;const m=u[p];if(m>=f)continue;const y=s[p+1];for(let b=s[p];b<y;b++){const v=a===null?b:a[b],A=i[v];u[A]===x&&(u[A]=m+1,c[A]=p,l[A]=v,d[w++]=A)}}return{order:d.subarray(0,w),parent:c,depth:u,visitedCount:w,predArc:l,...fc(n,r,l)}}function c3(n,e,t,r){const{rowPtr:o,colIdx:s,arcToEdge:i}=n;let a=o[t],c=o[t+1];for(;a<c;){const u=a+c>>>1;s[u]<r?a=u+1:c=u}const l=o[t+1];for(;a<l&&s[a]===r&&i[a]!==i[e];)a++;return a}function l3(n,e,t={}){const r=ai(n,e),{nodeCount:o,rowPtr:s,colIdx:i}=n,a=t.alpha??1,c=t.beta??18;let l=null;const u=new Uint32Array(o).fill(x),d=new Uint32Array(o).fill(x),f=new Uint32Array(o).fill(x),h=new Uint32Array(o);h[0]=r,f[r]=0;let g=0,w=1;const p=n.inDegree();let m=n.arcCount-p[r],y=!1;for(let b=0;g<w;b++){const v=w-g;if(y)y=v>=o/c;else{let E=0;for(let I=g;I<w;I++)E+=s[h[I]+1]-s[h[I]];y=E>m/a}const A=w;if(y){l??(l=n.reverse());for(let E=0;E<o;E++){if(f[E]!==x)continue;const I=l.rowPtr[E+1];for(let k=l.rowPtr[E];k<I;k++){const N=l.colIdx[k];if(f[N]===b){u[E]=N,d[E]=n.directed?l.fwdArc[k]:c3(n,k,N,E),f[E]=b+1,h[w++]=E;break}}}}else{for(let E=g;E<A;E++){const I=h[E],k=s[I+1];for(let N=s[I];N<k;N++){const C=i[N];f[C]===x&&(u[C]=I,d[C]=N,f[C]=b+1,h[w++]=C)}}h.subarray(A,w).sort()}for(let E=A;E<w;E++)m-=p[h[E]];g=A}return{order:h.subarray(0,w),parent:u,depth:f,visitedCount:w,predArc:d,...fc(n,r,d)}}const hc=2;function Yf(n,e={}){const{nodeCount:t}=n,r=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n],o=new Uint8Array(t).fill(hc),s=new Uint32Array(t);for(let a=0;a<t;a++){if(o[a]!==hc)continue;o[a]=0;let c=0,l=0;for(s[l++]=a;c<l;){const u=s[c++];for(const{rowPtr:d,colIdx:f}of r){const h=d[u+1];for(let g=d[u];g<h;g++){const w=f[g];if(o[w]===hc)o[w]=o[u]^1,s[l++]=w;else if(o[w]===o[u])return{bipartite:!1,sides:null}}}}}const i=At(t);for(let a=0;a<t;a++)o[a]===1&&pn(i,a,!0);return{bipartite:!0,sides:i}}function gc(n,e,t){const{rowPtr:r,colIdx:o,weights:s}=e,i=new Float64Array(n).fill(1/0),a=new Uint32Array(n),c=s===null?null:new Yn(n),l=new Uint8Array(n);return{dist:i,reached:a,run(u){let d=0;if(i[u]=0,a[d++]=u,c===null||s===null){for(let f=0;f<d;f++){const h=a[f];if(!(i[h]>=t))for(let g=r[h],w=r[h+1];g<w;g++){const p=o[g];i[p]===1/0&&(i[p]=i[h]+1,a[d++]=p)}}return d}for(c.push(u,0);!c.isEmpty();){const f=c.pop();if(l[f]=1,!(i[f]>=t))for(let h=r[f],g=r[f+1];h<g;h++){const w=o[h];if(l[w]===1)continue;const p=i[f]+s[h];p<i[w]&&(i[w]===1/0&&(a[d++]=w),i[w]=p,c.pushOrDecrease(w,p))}}return d},clear(u){for(let d=0;d<u;d++)i[a[d]]=1/0,l[a[d]]=0}}}function Xf(n,e,t,r,o){return n.harmonic===!0?n.normalized===!0&&e>1?o/(e-1):o:r<=0?0:n.normalized===!0&&e>1?t/r/(e-1):1/r}function Qf(n,e,t,r){const o=n.run(r);let s=0,i=0;for(let a=1;a<o;a++){const c=n.dist[n.reached[a]];s+=c,i+=c>0?1/c:0}return n.clear(o),Xf(e,t,o-1,s,i)}function wc(n,e,t){const r=e.weighted===!0;if(!t||!n.directed)return{rowPtr:n.rowPtr,colIdx:n.colIdx,weights:r?e.weights??n.weights:null};const o=n.reverse(),s=e.weights;let i=null;return r&&(i=s===void 0?o.weights:Float64Array.from(o.fwdArc,a=>s[a])),{rowPtr:o.rowPtr,colIdx:o.colIdx,weights:i}}function Jf(n,e={}){const t=n.nodeCount,r=e.cutoff??1/0,o=new Float64Array(t);if(e.sources===void 0&&e.k===void 0){const u=gc(t,wc(n,e,!1),r);for(let d=0;d<t;d++)o[d]=Qf(u,e,t,d);return{scores:o,iterations:t,converged:!0,sourcesUsed:t}}const s=is(n,e.sources,e.k,"closenessCentrality"),i=gc(t,wc(n,e,!0),r),a=new Float64Array(t),c=new Float64Array(t),l=new Uint32Array(t);for(const u of s){const d=i.run(u);for(let f=1;f<d;f++){const h=i.reached[f],g=i.dist[h];a[h]+=g,c[h]+=g>0?1/g:0,l[h]+=1}i.clear(d)}for(let u=0;u<t;u++)o[u]=Xf(e,t,l[u],a[u],c[u]);return{scores:o,iterations:s.length,converged:!0,sourcesUsed:s.length}}function u3(n,e,t={}){const r=xe(n,e);if(!Number.isInteger(r)||r<0||r>=n.nodeCount)throw Q(new RangeError(`nodeClosenessCentrality: node must be an index in [0, ${n.nodeCount}), got ${r}`),"E_BAD_NODE");const o=gc(n.nodeCount,wc(n,t,!1),t.cutoff??1/0);return Qf(o,t,n.nodeCount,r)}function Zf(n,e,t,r,o){let s=n.rowPtr[t];const i=n.rowPtr[t+1];let a=e.rowPtr[r];const c=e.rowPtr[r+1];let l=0;for(;s<i&&a<c;){const u=n.colIdx[s],d=e.colIdx[a];if(u===d)for(l+=o===void 0?1:o(u),s++,a++;a<c&&e.colIdx[a]===d;)a++;else u<d?s++:a++}return l}function d3(n,e,t,r={}){return Zf(n,r.directed===!0?n.reverse():n,e,t)}class eo{constructor(e){this.parent=new Uint32Array(e),this.rank=new Uint32Array(e);for(let t=0;t<e;t++)this.parent[t]=t}find(e){let t=e;for(;this.parent[t]!==t;)this.parent[t]=this.parent[this.parent[t]],t=this.parent[t];return t}union(e,t){const r=this.find(e),o=this.find(t);return r===o?!1:(this.rank[r]<this.rank[o]?this.parent[r]=o:this.rank[r]>this.rank[o]?this.parent[o]=r:(this.parent[o]=r,this.rank[r]++),!0)}toLabels(){const e=new Uint32Array(this.parent.length);for(let t=0;t<e.length;t++)e[t]=this.find(t);return Je(e)}}function We(n,e){let t=null;return{labels:n,count:e,groups(){if(t===null){const r=new Uint32Array(e);for(let i=0;i<n.length;i++)r[n[i]]++;const o=[];for(let i=0;i<e;i++)o.push(new Uint32Array(r[i]));const s=new Uint32Array(e);for(let i=0;i<n.length;i++){const a=n[i];o[a][s[a]++]=i}t=o}return t}}}function eh(n){const e=new eo(n.nodeCount),t=n.edgeList();for(let s=0;s<n.edgeCount;s++)e.union(t.src[s],t.dst[s]);const{labels:r,count:o}=e.toLabels();return We(r,o)}function th(n){if(n.directed)throw Q(new Error("Connected components requires an undirected graph. Use weaklyConnectedComponents, or pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");return eh(n)}function nh(n){return eh(n)}function rh(n,e){const{rowPtr:t,colIdx:r}=n;for(let o=0;o<n.nodeCount;o++){let s=-1;for(let i=t[o],a=t[o+1];i<a;i++)r[i]!==s&&(s=r[i],e[o]++)}}function f3(n,e={}){const t=new Float64Array(n.nodeCount),r=n.directed?e.mode??"total":"out";r!=="in"&&rh(n,t),r!=="out"&&rh(n.reverse(),t);const o=n.nodeCount-1;if(e.normalized===!0&&o>0)for(let s=0;s<t.length;s++)t[s]/=o;return t}function oh(n){const{src:e,dst:t}=n.edgeList(),r=new Uint32Array(n.nodeCount),o=new Uint32Array(n.nodeCount);for(let s=0;s<e.length;s++)o[e[s]]++,r[t[s]]++;return{inDegree:r,outDegree:o}}class sh{constructor(e){this.min=new Yn(e,!0)}isEmpty(){return this.min.isEmpty()}has(e){return this.min.has(e)}keyOf(e){return-this.min.keyOf(e)}push(e,t){this.min.push(e,-t)}pushOrIncrease(e,t){this.min.pushOrDecrease(e,-t)}pop(){return this.min.pop()}}function ih(n){const e=new Uint32Array(n.arcCount),t=n.rowPtr.slice(0,n.nodeCount),{src:r}=n.edgeList();for(let o=0;o<n.edgeCount;o++)e[t[r[o]]++]=n.edgeToArc[o];return e}function ah(n,e,t){const r=new Float64Array(n.nodeCount);for(let o=0;o<n.nodeCount;o++){let s=0;for(let i=n.rowPtr[o];i<n.rowPtr[o+1];i++)s+=t===null?1:t[e[i]];r[o]=s}return r}function pc(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t];if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function h3(n,e,t){if(n===void 0)return null;if(n.length!==e)throw Q(new RangeError(`${t} has ${String(n.length)} entries; the graph has ${String(e)} nodes`),"E_BAD_OPTION");const r=Float64Array.from(n);return pc(r),r}function ch(n,e){if(e===void 0)return n.weights;if(e.length!==n.arcCount)throw Q(new RangeError(`weights has ${String(e.length)} entries; the graph has ${String(n.arcCount)} arcs`),"E_BAD_OPTION");return e}function g3(n){if(n<0||n>1)throw Q(new Error("Damping factor must be between 0 and 1"),"E_BAD_OPTION")}class w3{constructor(e,t={}){if(!e.directed)throw Q(new Error("DeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.active=new Uint8Array(e.nodeCount).fill(1)}compute(e={}){return this.run(e,!1)}update(e,t={}){const{s:r}=this,o=r.reverse(),s=new Uint8Array(r.nodeCount);for(let i=0;i<e.length;i++){const a=e[i];if(!(!Number.isInteger(a)||a<0||a>=r.nodeCount)){s[a]=1;for(let c=o.rowPtr[a];c<o.rowPtr[a+1];c++)s[o.colIdx[c]]=1;for(let c=r.rowPtr[a];c<r.rowPtr[a+1];c++)s[r.colIdx[c]]=1}}return this.active=s,this.run(t,e.length>0)}run(e,t){const r=e.dampingFactor??.85,o=e.tolerance??1e-6,s=e.maxIterations??100,i=e.deltaThreshold??o/10;g3(r);const{s:a,order:c,scores:l}=this,u=a.nodeCount;if(u===0)return new Float64Array(0);const d=h3(e.personalization,u,"personalization"),f=e.weighted===!0?this.weights:null,h=(1-r)/u;let g=this.active.reduce((w,p)=>w+p,0);for(let w=0;(g>0||w===0&&t)&&w<s;w++){const p=new Float64Array(u);let m=0;for(let b=0;b<u;b++)a.rowPtr[b]===a.rowPtr[b+1]&&(m+=l[b]+this.deltas[b]);if(m>0){const b=r*m/u;for(let v=0;v<u;v++)p[v]+=d===null?b:b*d[v]}for(let b=0;b<u;b++){const v=this.deltas[b];if(this.active[b]===0||Math.abs(v)<i)continue;l[b]+=v;const A=this.outW[b];if(A>0)for(let E=a.rowPtr[b];E<a.rowPtr[b+1];E++){const I=c[E];p[a.colIdx[I]]+=r*v*((f===null?1:f[I])/A)}}let y=0;g=0;for(let b=0;b<u;b++){p[b]+=d===null?h:(1-r)*d[b];const v=Math.abs(p[b]);y=Math.max(y,v),this.active[b]=v>=i?1:0,g+=this.active[b]}if(this.deltas=p,y<o)break}return pc(l),l.slice()}}class p3{constructor(e,t={}){if(!e.directed)throw Q(new Error("PriorityDeltaPageRank requires a directed graph"),"E_NEEDS_DIRECTED");this.s=e,this.order=ih(e),this.weights=ch(e,t.weights),this.outW=ah(e,this.order,this.weights),this.scores=new Float64Array(e.nodeCount),this.deltas=new Float64Array(e.nodeCount).fill(1/e.nodeCount),this.heap=new sh(e.nodeCount);for(let r=0;r<e.nodeCount;r++)this.heap.push(r,1/e.nodeCount)}computeWithPriority(e={}){const t=e.dampingFactor??.85,r=e.tolerance??1e-6,o=e.maxIterations??100,s=e.deltaThreshold??r/10,{s:i,order:a,scores:c,deltas:l,heap:u}=this,d=i.nodeCount,f=e.weighted===!0?this.weights:null;let h=0,g=0;for(;!u.isEmpty()&&h<o;){const w=u.pop(),p=l[w];if(Math.abs(p)<s)continue;c[w]+=p,l[w]=0;const m=f===null?i.rowPtr[w+1]-i.rowPtr[w]:this.outW[w];if(m>0)for(let y=i.rowPtr[w];y<i.rowPtr[w+1];y++){const b=a[y],v=i.colIdx[b],A=l[v]+t*p*((f===null?1:f[b])/m);l[v]=A,Math.abs(A)>=s&&u.pushOrIncrease(v,Math.abs(A))}if(g++,g%1e3===0){let y=0;for(let b=0;b<d;b++)y=Math.max(y,Math.abs(l[b]));if(y<r)break}h++}for(let w=0;w<d;w++)Math.abs(l[w])>=s&&(c[w]+=l[w]);return pc(c),c.slice()}}const mc=0,yc=1,m3=2;function bc(n){return{state:new Uint8Array(n),parent:new Uint32Array(n).fill(x),predArc:new Uint32Array(n).fill(x),depth:new Uint32Array(n).fill(x),cursor:new Uint32Array(n),stack:new Uint32Array(n),pre:new Uint32Array(n),post:new Uint32Array(n),preCount:0,postCount:0,backArc:!1}}function y3(n,e,t,r){const{rowPtr:o,colIdx:s}=n,{state:i,parent:a,predArc:c,depth:l,cursor:u,pre:d}=t,f=u[e]++,h=r===null?f:r[f],g=s[h];return i[g]===mc?(i[g]=yc,a[g]=e,c[g]=h,l[g]=l[e]+1,u[g]=o[g],d[t.preCount++]=g,g):(i[g]===yc&&(t.backArc=!0),x)}function vc(n,e,t,r,o){const{rowPtr:s}=n,{state:i,depth:a,cursor:c,stack:l,pre:u,post:d}=t;let f=0;if(i[e]=yc,a[e]=0,c[e]=s[e],u[t.preCount++]=e,l[f++]=e,e!==r)for(;f>0;){const h=l[f-1];if(c[h]<s[h+1]){const g=y3(n,h,t,o);if(g!==x&&(l[f++]=g,g===r))return}else i[h]=m3,d[t.postCount++]=h,f--}}function lh(n,e,t={}){const r=ai(n,e),o=ci(n,t.arcOrder),s=Hf(n,t.target),i=bc(n.nodeCount),a=t.order==="post";return vc(n,r,i,a?x:s,o),{order:a?i.post.subarray(0,i.postCount):i.pre.subarray(0,i.preCount),parent:i.parent,depth:i.depth,visitedCount:i.preCount,predArc:i.predArc,...fc(n,r,i.predArc)}}function b3(n){return n.directed?v3(n):A3(n)}function v3(n){const{nodeCount:e}=n,t=bc(e);for(let r=0;r<e&&!t.backArc;r++)t.state[r]===mc&&vc(n,r,t,x,null);return t.backArc}function A3(n){const{nodeCount:e,rowPtr:t,colIdx:r}=n,o=new eo(e);for(let s=0;s<e;s++){const i=t[s+1];for(let a=t[s];a<i;a++){const c=r[a];if(c===s||c>s&&(a===t[s]||r[a-1]!==c)&&!o.union(s,c))return!0}}return!1}function E3(n,e={}){if(!n.directed)throw Q(new Error("Topological sort requires a directed graph"),"E_NEEDS_DIRECTED");const t=ci(n,e.arcOrder),r=bc(n.nodeCount);for(let o=0;o<n.nodeCount&&!r.backArc;o++)r.state[o]===mc&&vc(n,o,r,x,t);return r.backArc?null:r.post.reverse()}function uh(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=e.startVector;if(s!==void 0&&s.length!==t)throw Q(new Error(`eigenvectorCentrality: startVector has ${String(s.length)} entries for ${String(t)} nodes`),"E_BAD_OPTION");let i=new Float64Array(t);if(t===0)return{scores:i,iterations:0,converged:!0};const a=_3(n,e.mode??"in");if(I3(a,t))return{scores:i,iterations:0,converged:!0};for(let d=0;d<t;d++)a.rowPtr[d+1]>a.rowPtr[d]&&(i[d]=s===void 0?1:s[d]);fh(i);let c=new Float64Array(t),l=0,u=!1;for(;l<r&&!u;l++){for(let f=0;f<t;f++){let h=i[f];const g=a.rowPtr[f+1];for(let w=a.rowPtr[f];w<g;w++)h+=i[a.colIdx[w]];c[f]=h}fh(c);let d=0;for(let f=0;f<t;f++)d+=Math.abs(c[f]-i[f]);[i,c]=[c,i],u=d<t*o}if(!u)throw new Mf("eigenvectorCentrality",r,o);return e.normalized!==!1&&dh(i),{scores:i,iterations:l,converged:u}}function dh(n){let e=1/0,t=0;for(const s of n)e=Math.min(e,s),t=Math.max(t,s);const r=t-e,o=t>0?1:0;for(let s=0;s<n.length;s++)n[s]=r>0?(n[s]-e)/r:o}function _3(n,e){const t=n.nodeCount,r=!n.directed||e==="out"?n:n.reverse(),o=n.directed&&e==="total",s=o?n.rowPtr:new Uint32Array(t+1),i=o?n.colIdx:new Uint32Array(0),a=new Uint32Array(t+1),c=new Uint32Array(r.colIdx.length+i.length);let l=0;for(let u=0;u<t;u++){let d=r.rowPtr[u];const f=r.rowPtr[u+1];let h=s[u];const g=s[u+1],w=l;for(;d<f||h<g;){const p=h>=g||d<f&&r.colIdx[d]<=i[h]?r.colIdx[d++]:i[h++];(l===w||c[l-1]!==p)&&(c[l++]=p)}a[u+1]=l}return{rowPtr:a,colIdx:c.subarray(0,l)}}function I3(n,e){const t=new Uint32Array(e);for(const s of n.colIdx)t[s]++;const r=new Uint32Array(e);let o=0;for(let s=0;s<e;s++)t[s]===0&&(r[o++]=s);for(let s=0;s<o;s++){const i=r[s];for(let a=n.rowPtr[i];a<n.rowPtr[i+1];a++)--t[n.colIdx[a]]===0&&(r[o++]=n.colIdx[a])}return o===e}function fh(n){let e=0;for(const t of n)e+=t*t;if(e=Math.sqrt(e),e>0)for(let t=0;t<n.length;t++)n[t]/=e}function to(n,e){const t=new Uint32Array(e),r=e>0&&_e(n,0);let o=!1;for(let s=0;s<e;s++)_e(n,s)!==r&&(t[s]=1,o=!0);return e===0?We(t,0):We(t,o?2:1)}function Ac(n,e){const t=n.edgeList(),r=new Float64Array(n.edgeCount);for(let o=0;o<n.edgeCount;o++)r[o]=e!==void 0?e[t.arc[o]]:t.weights?.[o]??1;return r}function Ec(n,e,t,r,o){const{src:s,dst:i}=n.edgeList(),a=[];for(let c=0;c<n.edgeCount;c++){const l=_e(e,s[c]);(t?l&&!_e(e,i[c]):l!==_e(e,i[c]))&&(!o||r[c]>0)&&a.push(c)}return Uint32Array.from(a)}function k3(n,e){const t=n.nodeCount,r=n.edgeCount,{src:o,dst:s}=n.edgeList(),i=new Uint32Array(2*r),a=new Uint32Array(2*r);i.set(o),i.set(s,r),a.set(s),a.set(o,r);const c=sc({directed:!0,nodeCount:t,src:i,dst:a}),{rowPtr:l,colIdx:u,arcToEdge:d,edgeToArc:f}=c,h=c.arcCount,g=new Float64Array(h),w=new Uint32Array(h),p=new Uint8Array(h);for(let E=0;E<t;E++)for(let I=l[E];I<l[E+1];I++){const k=I>l[E]&&u[I]===u[I-1]?w[I-1]:I;w[I]=k;const N=d[I];(N<r||!n.directed)&&(p[k]=1,g[k]+=Math.max(e[N<r?N:N-r],0))}const m=new Uint32Array(h);for(let E=0;E<h;E++)if(w[E]===E){const I=d[E];m[E]=w[f[I<r?I+r:I-r]]}const y=new Uint32Array(h),b=new Uint32Array(t),v=new Uint8Array(h),A=(E,I)=>{v[I]===0&&(v[I]=1,y[l[E]+b[E]++]=I)};for(let E=0;E<r;E++)A(o[E],w[f[E]]),n.directed||A(s[E],w[f[E+r]]);return{rowPtr:l,colIdx:u,arcToEdge:d,capacity:g,groupOf:w,twin:m,order:y,placed:b,inOrder:v,real:p}}function _c(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=n.nodeCount;if(!(Number.isInteger(o)&&o>=0&&o<i&&Number.isInteger(s)&&s>=0&&s<i))throw Q(new RangeError(`source ${String(o)} and sink ${String(s)} must be node indices below ${i}`),"E_BAD_NODE");if(o===s)throw Q(new RangeError(`source and sink are the same node (${o})`),"E_BAD_OPTION");const a=Ac(n,r.weights),c=k3(n,a),l=new Float64Array(c.colIdx.length),u=new Uint32Array(i),d=r.algorithm==="ford-fulkerson"?C3:x3;let f=0;for(;d(c,o,s,u);)f+=S3(c,o,s,u,l);const h=N3(c,o);return{...to(h,n.nodeCount),maxFlow:f,flow:P3(n,c,a,l),sourceSide:h,cutEdges:Ec(n,h,n.directed,a,!0)}}function S3(n,e,t,r,o){const{colIdx:s,twin:i}=n;let a=1/0;for(let c=t;c!==e;c=s[i[r[c]]])a=Math.min(a,n.capacity[r[c]]);for(let c=t;c!==e;){const l=r[c],u=i[l];n.capacity[l]-=a,n.capacity[u]+=a,n.inOrder[u]===0&&(n.inOrder[u]=1,n.order[n.rowPtr[c]+n.placed[c]++]=u),n.real[l]===1?o[l]+=a:o[u]-=a,c=s[u]}return a}function P3(n,e,t,r){const o=n.edgeCount,s=new Float64Array(o),{rowPtr:i,colIdx:a,arcToEdge:c,groupOf:l}=e;for(let u=0;u<n.nodeCount;u++)for(let d=i[u];d<i[u+1];d++){const f=a[d];if(l[d]!==d||f<=u)continue;const h=r[d]-r[e.twin[d]];if(h===0)continue;const g=h>0?d:e.twin[d],w=i[a[e.twin[g]]+1];let p=Math.abs(h),m=-1,y=1;for(let b=g;b<w&&l[b]===g;b++){const v=c[b];if(!(v>=o&&n.directed)){if(m>=0){const A=Math.min(p,Math.max(t[m],0));s[m]+=y*A,p-=A}m=v<o?v:v-o,y=v<o?1:-1}}m>=0&&(s[m]+=y*p)}return s}function hh(n,e,t,r={}){const o=xe(n,e),s=xe(n,t),i=_c(n,o,s,{...r,algorithm:r.algorithm??"ford-fulkerson"});return{...to(i.sourceSide,n.nodeCount),cutValue:i.maxFlow,side:i.sourceSide,cutEdges:i.cutEdges}}function x3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n;r.fill(x);const l=new Uint32Array(r.length);let u=0,d=0;for(l[d++]=e;u<d;){const f=l[u++],h=o[f]+a[f];for(let g=o[f];g<h;g++){const w=i[g],p=s[w];if(c[w]>0&&p!==e&&r[p]===x){if(r[p]=w,p===t)return!0;l[d++]=p}}}return!1}function C3(n,e,t,r){const{rowPtr:o,colIdx:s,order:i,placed:a,capacity:c}=n,l=r.length;r.fill(x);const u=new Uint8Array(l),d=new Uint32Array(l),f=new Uint32Array(l);let h=0;for(d[h++]=e,u[e]=1,f[e]=o[e];h>0;){const g=d[h-1],w=f[g]++;if(w>=o[g]+a[g]){h--;continue}const p=i[w],m=s[p];if(c[p]>0&&u[m]===0){if(r[m]=p,m===t)return!0;u[m]=1,f[m]=o[m],d[h++]=m}}return!1}function N3(n,e){const{rowPtr:t,colIdx:r,order:o,placed:s,capacity:i}=n,a=t.length-1,c=At(a),l=new Uint32Array(a);let u=0,d=0;for(l[d++]=e,pn(c,e,!0);u<d;){const f=l[u++],h=t[f]+s[f];for(let g=t[f];g<h;g++){const w=r[o[g]];i[o[g]]>0&&!_e(c,w)&&(pn(c,w,!0),l[d++]=w)}}return c}function no(n){let e=n>>>0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}const T3=2147483647;function O3(n,e){for(let t=0;t<n.nodeCount;t++){const r=n.rowPtr[t+1];for(let o=n.rowPtr[t];o<r;o++)if(n.colIdx[o]!==t&&(e===null||e[o]>0))return!0}return!1}function gh(n,e,t){for(let r=0;r<e.length;r++){if(t!==null&&t[r]===1)continue;const o=n.collect(r,e);if(o!==0&&n.voteOf(e[r])!==o)return!1}return!0}function Ic(n,e){if(e===null)return n.weights;const t=new Float64Array(n.arcCount);for(let r=0;r<t.length;r++)t[r]=e[n.arcToEdge[r]];return t}function li(n){const e=n.edges.byRole("weight");return e!==null&&e.dtype==="f64"?e.data:null}function kc(n,e){const t=e?Ic(n,li(n)):null;if(t!==null)for(let o=0;o<t.length;o++){const s=t[o];if(!(s>=0)||s===1/0)throw Q(new RangeError(`arc ${o} has weight ${s}; label propagation needs finite, non-negative weights`),"E_BAD_WEIGHT")}const r=n.directed?n.reverse():null;return{sides:r===null?1:2,rowPtrs:[n.rowPtr,r===null?n.rowPtr:r.rowPtr],colIdxs:[n.colIdx,r===null?n.colIdx:r.colIdx],arcWeights:[t,t===null||r===null?t:Ic(r,li(n))],weights:t}}function Sc(n,e,t){if(!Number.isInteger(e)||e<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${e}`),"E_BAD_OPTION");if(t!==null&&!Number.isInteger(t))throw Q(new RangeError(`randomSeed must be a finite integer, got ${t}`),"E_BAD_OPTION");if(e*n>Number.MAX_SAFE_INTEGER)throw Q(new RangeError(`maxIterations * nodeCount (${e} * ${n}) exceeds Number.MAX_SAFE_INTEGER`),"E_BAD_OPTION")}class Pc{constructor(e,t,r){this.rows=t,this.epoch=-1,this.count=0,this.acc=new Float64Array(e),this.stamp=new Int32Array(e).fill(-1),this.touched=new Uint32Array(e),this.seen=r?null:new Int32Array(e).fill(-1)}collect(e,t){++this.epoch===T3&&(this.stamp.fill(-1),this.seen?.fill(-1),this.epoch=0);const{acc:r,stamp:o,touched:s,seen:i,rows:a}=this,c=this.epoch;let l=0;for(let d=0;d<a.sides;d++){const f=a.rowPtrs[d],h=a.colIdxs[d],g=a.arcWeights[d],w=f[e+1];for(let p=f[e];p<w;p++){const m=h[p];if(m===e)continue;if(i!==null){if(i[m]===c)continue;i[m]=c}const y=t[m];if(y===x)continue;const b=g===null?1:g[p];o[y]!==c?(o[y]=c,r[y]=b,s[l++]=y):r[y]+=b}}this.count=l;let u=0;for(let d=0;d<l;d++)r[s[d]]>u&&(u=r[s[d]]);return u}voteOf(e){return this.stamp[e]===this.epoch?this.acc[e]:0}}function wh(n,e,t,r,o,s,i){const a=n.nodeCount,c=no(i),l=new Pc(a,e,t),u=a+1,d=new Uint32Array(u),f=new Uint8Array(a);let h=0;for(let v=0;v<a;v++)(o===null||o[v]===0)&&(d[h++]=v,f[v]=1);for(let v=h-1;v>=1;v--){const A=Math.floor(c()*(v+1)),E=d[v];d[v]=d[A],d[A]=E}let g=0,w=h;const p=s*a;let m=0;const{touched:y,acc:b}=l;for(;h>0&&m<p;){const v=d[g];g=g+1===u?0:g+1,h--,f[v]=0,m++;const A=l.collect(v,r);if(A===0)continue;let E=0,I=0;for(let k=0;k<l.count;k++){const N=y[k];b[N]===A&&(I++,(I===1||c()*I<1)&&(E=N))}if(E!==r[v]){r[v]=E;for(let k=0;k<e.sides;k++){const N=e.rowPtrs[k],C=e.colIdxs[k],O=N[v+1];for(let T=N[v];T<O;T++){const $=C[T];f[$]===0&&r[$]!==E&&(o===null||o[$]===0)&&(f[$]=1,d[w]=$,w=w+1===u?0:w+1,h++)}}}}return{visits:m,size:h}}function ph(n,e={}){const t=e.maxIterations??100,r=e.randomSeed??42,o=e.weighted??!0,s=n.nodeCount;Sc(s,t,r);const i=kc(n,o),a=new Uint32Array(s);for(let f=0;f<s;f++)a[f]=f;if(s===0||t===0){const{labels:f,count:h}=Je(a);return{...We(f,h),iterations:0,converged:!O3(n,i.weights)}}const{visits:c,size:l}=wh(n,i,o,a,null,t,r),{labels:u,count:d}=Je(a);return{...We(u,d),iterations:Math.ceil(c/s),converged:l===0}}function $3(n,e,t={}){const r=t.maxIterations??100,o=t.randomSeed??42,s=t.weighted??!0,i=n.nodeCount;if(e.length!==i)throw Q(new RangeError(`seeds has ${e.length} entries; the snapshot has ${i} nodes`),"E_BAD_OPTION");Sc(i,r,o);const a=kc(n,s),c=new Uint32Array(i),l=new Uint8Array(i),u=new Map;for(let p=0;p<i;p++){const m=e[p];if(m===x){c[p]=x;continue}let y=u.get(m);y===void 0&&(y=p,u.set(m,p)),c[p]=y,l[p]=1}const{visits:d,size:f}=wh(n,a,s,c,l,r,o),h=f===0||r===0&&gh(new Pc(i,a,s),c,l);R3(a,c);const{labels:g,count:w}=Je(c);return{...We(g,w),iterations:i===0?0:Math.ceil(d/i),converged:h}}function R3(n,e){const t=[];for(let r=0;r<e.length;r++)if(e[r]===x)for(e[r]=r,t.push(r);t.length>0;)D3(n,e,t.pop(),r,t)}function D3(n,e,t,r,o){for(let s=0;s<n.sides;s++){const i=n.rowPtrs[s],a=n.colIdxs[s],c=n.arcWeights[s],l=i[t+1];for(let u=i[t];u<l;u++){const d=a[u];e[d]===x&&(c===null||c[u]>0)&&(e[d]=r,o.push(d))}}}function mh(n,e={}){const t=e.maxIterations??100,r=e.weighted??!0,o=n.nodeCount;Sc(o,t,null);const s=kc(n,r),i=new Pc(o,s,r),{touched:a,acc:c}=i;let l=new Uint32Array(o),u=new Uint32Array(o),d=new Uint32Array(o).fill(x);const f=new Uint32Array(o);for(let b=0;b<o;b++)l[b]=b,f[b]=L3(b);let h=0,g=0,w=!1;for(;g<2&&h<t&&!w;){const b=h%2===0;h++;let v=!1;for(let A=0;A<o;A++){const E=l[A];u[A]=E;const I=i.collect(A,l);if(I===0||i.voteOf(E)===I)continue;let k=x;for(let N=0;N<i.count;N++){const C=a[N];c[C]===I&&(k===x||f[C]<f[k])&&(k=C)}(b?f[k]>f[E]:f[k]<f[E])&&(u[A]=k,v=!0)}w=v&&M3(u,d),[d,l,u]=[l,u,d],g=v?0:g+1}const p=g>=2||gh(i,l,null),{labels:m,count:y}=Je(l);return{...We(m,y),iterations:h,converged:p}}function L3(n){return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function M3(n,e){for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function xc(n,e,t={}){const r=t.resolution??1,o=t.weights??n.weights;if(e.length!==n.nodeCount)throw Q(new RangeError(`labels has ${e.length} entries; the snapshot has ${n.nodeCount} nodes`),"E_BAD_OPTION");if(o!==null&&o.length!==n.arcCount)throw Q(new RangeError(`weights has ${o.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const s=new Map,i=new Map,a=(u,d,f)=>{d!==x&&u.set(d,(u.get(d)??0)+f)};let c=0;for(let u=0;u<n.nodeCount;u++){const d=n.rowPtr[u+1];for(let f=n.rowPtr[u];f<d;f++){const h=n.colIdx[f],g=o===null?1:o[f],w=n.directed||h===u?2*g:g;c+=w,n.directed?(a(s,e[u],g),a(s,e[h],g)):a(s,e[u],w),e[u]===e[h]&&a(i,e[u],w)}}if(c===0)return 0;let l=0;for(const[u,d]of s){const f=d/c;l+=(i.get(u)??0)/c-r*f*f}return l}const U3=1e-10;function F3(n,e){const t=new eo(n.nodeCount),r=n.edgeList();for(let o=0;o<n.edgeCount;o++)_e(e,o)&&t.union(r.src[o],r.dst[o]);return t.toLabels()}function yh(n,e={}){if(n.directed)throw Q(new Error("Girvan-Newman requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.maxCommunities??0,r=e.minCommunitySize??1,o=e.maxIterations??100,{nodeCount:s,edgeCount:i}=n,a=Ic(n,li(n)),c=At(i,!0),l=[],u=[],d=[],f=()=>{const{labels:g,count:w}=F3(n,c);l.push(g),d.push(w),u.push(xc(n,g,a===null?{}:{weights:a}));const p=new Uint32Array(w);for(let m=0;m<s;m++)p[g[m]]++;return p.filter(m=>m>=r).length};f();for(let g=0;g<o&&z2(c,i)>0;g++){const w=dc(n,{alive:c}).scores;let p=-1/0;for(let y=0;y<i;y++)_e(c,y)&&w[y]>p&&(p=w[y]);for(let y=0;y<i;y++)_e(c,y)&&Math.abs(w[y]-p)<U3&&pn(c,y,!1);const m=f();if(t>0&&m>=t||m===s)break}let h=0;for(let g=1;g<u.length;g++)(u[g]>u[h]||Number.isNaN(u[h])&&!Number.isNaN(u[g]))&&(h=g);return{...We(l[h],d[h]),bestLevel:h,levels:l,modularity:Float64Array.from(u)}}function B3(n,e={}){const{maxDepth:t=10,minClusterSize:r=2,tolerance:o=1e-6,maxIterations:s=100,seed:i=42,weighted:a=!0}=e,c=n.nodeCount;if(c===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const l=no(i),u=a?n.weights:null;if(u!==null)for(let M=0;M<u.length;M++){const R=u[M];if(!(R>=0)||R===1/0)throw Q(new RangeError(`arc ${String(M)} has weight ${String(R)}; grsbm needs finite, non-negative weights`),"E_BAD_WEIGHT")}const d=a?n.weightedDegree():n.degree(),f=a?n.totalWeight():n.edgeCount,h=n.directed?1:2,g=!n.directed||!a,{rowPtr:w,colIdx:p}=n,m=new Int32Array(c).fill(-1),y=M=>{let R=0,D=0;for(let U=0;U<M.length;U++){const B=M[U];D+=d[B];for(let V=w[B];V<w[B+1];V++){const W=p[V];if(m[W]===m[B]){const q=u===null?1:u[V];R+=W===B?h*q:q}}}return g&&(R/=2),(R-D*D/(4*f))/f},b=M=>{if(f===0)return 0;let R=0;M.forEach((D,U)=>{for(let B=0;B<D.length;B++)m[D[B]]=U});for(const D of M)D.length>0&&(R+=y(D));for(const D of M)for(let U=0;U<D.length;U++)m[D[U]]=-1;return R},v=new Uint32Array(c);for(let M=0;M<c;M++)v[M]=M;const A=b([v]),E=[{serial:0,members:v,depth:0,modularity:A,spectralScore:0,left:x,right:x,split:null}],I=[A];let k=A;const N=new Int32Array(c).fill(-1);let C=1;for(let M=0;M<E.length;M++){const R=E[M],{members:D}=R,U=D.length;if(R.depth>=t||U<r*2||U<4)continue;const B=z3(D,N,n,u,l,o,s),V=Array.from({length:U},(ue,we)=>we).sort((ue,we)=>B[ue]-B[we]),W=Uint32Array.from(V,ue=>D[ue]);let q=Math.floor(U/2),K=-1/0;for(let ue=Math.floor(U*.2);ue<=Math.floor(U*.8);ue++){const we=b([W.subarray(0,ue),W.subarray(ue)]);we>K&&(K=we,q=ue)}const X=W.slice(0,q),H=W.slice(q),Y=Array.from(B).sort((ue,we)=>Math.abs(we)-Math.abs(ue)),ee=Math.abs(Y[Math.floor(U*.1)]),Z=[];for(let ue=0;ue<U&&Z.length<5;ue++)Math.abs(B[ue])>=ee&&Z.push(D[ue]);const J=Math.abs(Y[0]-Y[U-1]),ce=C++,de=C++,ne=K-b([D]);if(ne<=0)continue;k+=ne;const ve=(ue,we)=>({serial:ue,members:we,depth:R.depth+1,modularity:k,spectralScore:J,left:x,right:x,split:null});R.left=E.length,R.right=E.length+1,R.split={improvement:ne,bisectionModularity:k,keyNodes:Uint32Array.from(Z),spectralValues:B},E.push(ve(ce,X),ve(de,H)),I.push(k)}const O=new Uint32Array(c);let T=0;const $=[0];for(;$.length>0;){const M=E[$.pop()??0];if(M.left===x){for(const R of M.members)O[R]=T;T++}else $.push(M.right,M.left)}const{labels:L,count:F}=Je(O);return{...We(L,F),clusters:E,modularityScores:Float64Array.from(I)}}function z3(n,e,t,r,o,s,i){const a=n.length;for(let y=0;y<a;y++)e[n[y]]=y;const c=new Uint32Array(a+1),l=[],u=[],d=new Map;let f=0;for(let y=0;y<a;y++){const b=n[y];d.clear();let v=0;for(let A=t.rowPtr[b];A<t.rowPtr[b+1];A++){const E=e[t.colIdx[A]];if(E>=0&&E!==y){const I=r===null?1:r[A];d.set(E,(d.get(E)??0)-I),v+=I}}d.set(y,v),f=Math.max(f,v);for(const A of[...d.keys()].sort((E,I)=>E-I))l.push(A),u.push(d.get(A)??0);c[y+1]=l.length}for(let y=0;y<a;y++)e[n[y]]=-1;let h=new Float64Array(a);for(let y=0;y<a;y++)h[y]=o()-.5;const g=y=>{let b=0;for(const A of y)b+=A;const v=b/a;for(let A=0;A<a;A++)y[A]-=v},w=y=>{let b=0;for(const v of y)b+=v*v;return Math.sqrt(b)};g(h);const p=w(h);if(p>0)for(let y=0;y<a;y++)h[y]/=p;const m=2*f;for(let y=0;y<i;y++){const b=new Float64Array(a);for(let E=0;E<a;E++){let I=0;for(let k=c[E];k<c[E+1];k++)I+=u[k]*h[l[k]];b[E]=m*h[E]-I}g(b);const v=w(b);if(v<s)break;let A=0;for(let E=0;E<a;E++)b[E]/=v,A+=Math.abs(b[E]-h[E]);if(h=b,A<s)break}return h}function G3(n,e){const t=n.nodeCount;e.fill(x);const r=new Uint32Array(t);for(let o=0;o<t;o++){const s=o*t;e[s+o]=0,r[0]=o;let i=0,a=1;for(;i<a;){const c=r[i++],l=e[s+c]+1,u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++){const f=n.colIdx[d];e[s+f]===x&&(e[s+f]=l,r[a++]=f)}}}}function W3(n){const e=Math.max(0,2*n-1),t=Array.from({length:e},(s,i)=>i<n?`leaf-${i}`:`cluster-${i}`),r=Array.from({length:e},(s,i)=>i).sort((s,i)=>+(t[s]>t[i])-+(t[s]<t[i])),o=new Uint32Array(e);return r.forEach((s,i)=>o[s]=i),o}function V3(n,e={}){const t=e.linkage??"single";if(!["single","complete","average","ward"].includes(t))throw Q(new RangeError(`unknown linkage "${t}"`),"E_BAD_OPTION");const r=n.nodeCount,{hops:o,min:s,max:i,sum:a,count:c}=Lf("hierarchicalClustering",r,e.maxNodes,28*r*r,()=>({hops:new Uint32Array(r*r),min:new Uint32Array(r*r),max:new Uint32Array(r*r),sum:new Float64Array(r*r),count:new Float64Array(r*r)}));G3(n,o);for(let T=0;T<r*r;T++){const $=o[T];$!==x&&(s[T]=$,i[T]=$,a[T]=$,c[T]=1)}const l=Math.max(0,2*r-1),u=W3(r),d=new Uint32Array(l),f=new Float64Array(l),h=new Uint32Array(l);for(let T=0;T<r;T++)d[T]=T,f[T]=1;const g=[],w=[],p=[],m=(T,$)=>{const L=d[T]*r+d[$],F=c[L];if(F===0)return 1/0;switch(t){case"single":return s[L];case"complete":return i[L];case"average":return a[L]/F;default:return a[L]/F*(f[T]*f[$]/(f[T]+f[$]))}},y=(T,$)=>{const[L,F]=T<$?[T,$]:[$,T];return F<r?m(L,F):m(F,L)};let b=Array.from({length:r},(T,$)=>$);for(;b.length>1;){let T=1/0,$=-1,L=-1;for(const D of b)for(const U of b){if(u[D]>=u[U])continue;const B=y(D,U);B<T&&(T=B,$=D,L=U)}if($<0)break;const F=r+g.length;g.push($),w.push(L),p.push(T),h[F]=Math.max(h[$],h[L])+1,f[F]=f[$]+f[L];const M=d[$],R=d[L];for(const D of b){if(D===$||D===L)continue;const U=d[D];for(const[B,V,W]of[[M*r+U,M*r+U,R*r+U],[U*r+M,U*r+M,U*r+R]]){const q=c[V],K=c[W];if(q===0||K===0){const X=q===0?W:V;s[B]=s[X],i[B]=i[X]}else s[B]=Math.min(s[V],s[W]),i[B]=Math.max(i[V],i[W]);a[B]=a[V]+a[W],c[B]=q+K}}d[F]=M,b=b.filter(D=>D!==$&&D!==L),b.push(F)}const v=g.length,A=Uint32Array.from(g),E=Uint32Array.from(w),I=T=>{if(!(T>=0&&T<r+v))throw Q(new RangeError(`cluster ${T} is not in [0, ${r+v})`),"E_BAD_OPTION");const $=[],L=[T];for(;L.length>0;){const F=L.pop();F<r?$.push(F):L.push(E[F-r],A[F-r])}return Uint32Array.from($)},k=Uint32Array.from(b),N=Float64Array.from(p),C=new Uint32Array(v);for(let T=0;T<v;T++)C[T]=A[T]<r?A[T]:C[A[T]-r];const O=T=>T<r?T:C[T-r];return{nodeCount:r,left:A,right:E,distance:N,height:h.slice(0,r+v),roots:k,members:I,cut(T){const $=[],L=F=>{F<r||h[F]<=T?$.push(I(F)):(L(A[F-r]),L(E[F-r]))};return k.forEach(L),$},cutAt(T){let $=0;if("clusters"in T){const R=T.clusters;if(!Number.isInteger(R)||R<k.length||R>r)throw Q(new RangeError(`clusters must be an integer in [${k.length}, ${r}], got ${R}`),"E_BAD_OPTION");$=r-R}else{if(Number.isNaN(T.distance))throw Q(new RangeError("distance must not be NaN"),"E_BAD_OPTION");for(;$<v&&N[$]<=T.distance;)$++}const L=new eo(r);for(let R=0;R<$;R++)L.union(O(A[R]),O(E[R]));const{labels:F,count:M}=L.toLabels();return We(F,M)}}}function bh(n){let e=0;for(let r=0;r<n.length;r++)e+=n[r]*n[r];const t=Math.sqrt(e);if(t>0)for(let r=0;r<n.length;r++)n[r]/=t}function vh(n){let e=0;for(let t=0;t<n.length;t++)n[t]>e&&(e=n[t]);if(e>0)for(let t=0;t<n.length;t++)n[t]/=e}function Ah(n,e={}){const t=n.nodeCount,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.reverse(),i=e.weighted===!0?n.weights:null,a=e.weighted===!0?s.weights:null;let c=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),l=new Float64Array(t).fill(t===0?0:1/Math.sqrt(t)),u=new Float64Array(t),d=new Float64Array(t),f=0,h=!1;for(;f<r&&!h;f++){for(let w=0;w<t;w++){let p=0;const m=s.rowPtr[w+1];for(let v=s.rowPtr[w];v<m;v++)p+=c[s.colIdx[v]]*(a===null?1:a[v]);d[w]=p;let y=0;const b=n.rowPtr[w+1];for(let v=n.rowPtr[w];v<b;v++)y+=l[n.colIdx[v]]*(i===null?1:i[v]);u[w]=y}bh(d),bh(u);let g=0;for(let w=0;w<t;w++){const p=Math.abs(u[w]-c[w]);p>g&&(g=p);const m=Math.abs(d[w]-l[w]);m>g&&(g=m)}[c,u]=[u,c],[l,d]=[d,l],h=g<o}return e.normalized===!1&&(vh(c),vh(l)),{hubs:c,authorities:l,iterations:f,converged:h}}function Eh(n,e){let t=0,r=!1,o=x;for(let s=n.rowPtr[e];s<n.rowPtr[e+1];s++){const i=n.colIdx[s];i!==o&&(o=i,i===e?r=!0:t++)}return{degree:t,loop:r}}function _h(n){const e=new Float64Array(n.nodeCount),t=n.directed?n.reverse():null;for(let r=0;r<n.nodeCount;r++){const o=Eh(n,r),s=t===null?0:Eh(t,r).degree;e[r]=(o.degree*67108864+s)*2+(o.loop?1:0)}return e}function j3(n,e){const t=new Uint32Array(e),r=new Uint32Array(e).fill(x),o=new Uint8Array(e),s=new Uint8Array(e);let i=0;for(let a=0;a<e;a++){if(s[a]===1)continue;s[a]=1;let c=i;for(t[i++]=a;c<i;)i=q3(n,t[c++],{order:t,parent:r,parentView:o},s,i)}return{order:t,parent:r,parentView:o}}function q3(n,e,t,r,o){const{order:s,parent:i,parentView:a}=t;for(let c=0;c<n.length;c++){const{rowPtr:l,colIdx:u}=n[c];for(let d=l[e];d<l[e+1];d++){const f=u[d];r[f]===0&&(r[f]=1,i[f]=e,a[f]=c,s[o++]=f)}}return o}function Ih(n,e,t,r){const o=n.nodeCount;if(n.directed!==e.directed||o!==e.nodeCount)return;const s=_h(n),i=_h(e),a=s.slice().sort(),c=i.slice().sort();if(a.some((O,T)=>O!==c[T]))return;const l=n.directed?[n,n.reverse()]:[n],u=e.directed?[e,e.reverse()]:[e],{order:d,parent:f,parentView:h}=j3(l,o),g=new Uint32Array(o).fill(x),w=new Uint32Array(o).fill(x),p=u.map(()=>new Uint32Array(o)),m=u.map(()=>new Uint32Array(o));let y=0;const{nodeMatch:b,edgeMatch:v}=t,A=(O,T)=>{if(s[O]!==i[T]||b!==void 0&&!b(O,T,n,e))return!1;if(v!==void 0&&s[O]%2===1){const $=n.arcToEdge[n.findArc(O,O)],L=e.arcToEdge[e.findArc(T,T)];if(!v($,L,n,e))return!1}y++;for(let $=0;$<l.length;$++){const L=l[$],F=u[$];let M=0,R=x;for(let U=F.rowPtr[T];U<F.rowPtr[T+1];U++){const B=F.colIdx[U];B===R||B===T||(R=B,p[$][B]=y,m[$][B]=U,w[B]!==x&&M++)}let D=0;R=x;for(let U=L.rowPtr[O];U<L.rowPtr[O+1];U++){const B=L.colIdx[U];if(B===R||B===O)continue;R=B;const V=g[B];if(V!==x&&(p[$][V]!==y||(D++,v!==void 0&&!v(L.arcToEdge[U],F.arcToEdge[m[$][V]],n,e))))return!1}if(D!==M)return!1}return!0},E=new Uint32Array(o+1);let I=0,k=!1;const N=O=>{const T=f[d[O]];if(T===x)return{view:null,from:0,to:o};const $=u[h[d[O]]],L=g[T];return{view:$,from:$.rowPtr[L],to:$.rowPtr[L+1]}};if(o===0){r(g);return}let C=N(0);for(E[0]=C.from;!k;){const O=d[I];let T=!1;for(;E[I]<C.to;){const L=E[I]++,F=C.view===null?L:C.view.colIdx[L];if(!(C.view!==null&&L>C.from&&C.view.colIdx[L-1]===F)&&!(w[F]!==x||!A(O,F))){if(g[O]=F,w[F]=O,I===o-1){if(k=r(g),g[O]=x,w[F]=x,k)break;continue}I++,C=N(I),E[I]=C.from,T=!0;break}}if(k||T)continue;if(I===0)return;I--;const $=d[I];w[g[$]]=x,g[$]=x,C=N(I)}}function H3(n,e,t={}){let r=null;return Ih(n,e,t,o=>(r=o.slice(),!0)),{isomorphic:r!==null,mapping:r}}function K3(n,e,t={}){const r=[];return Ih(n,e,t,o=>(r.push(o.slice()),!1)),r}function kh(n){if(n.directed)throw Q(new Error("k-core requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const e=n.nodeCount,{rowPtr:t,colIdx:r}=n,o=new Uint32Array(e);let s=0;for(let f=0;f<e;f++){let h=0,g=-1;const w=t[f+1];for(let p=t[f];p<w;p++){const m=r[p];m!==f&&m!==g&&h++,g=m}o[f]=h,h>s&&(s=h)}const i=new Uint32Array(s+1);for(let f=0;f<e;f++)i[o[f]]++;let a=0;for(let f=0;f<=s;f++){const h=i[f];i[f]=a,a+=h}const c=new Uint32Array(e),l=new Uint32Array(e);for(let f=0;f<e;f++)l[f]=i[o[f]],c[l[f]]=f,i[o[f]]++;for(let f=s;f>0;f--)i[f]=i[f-1];i[0]=0;let u=0;for(let f=0;f<e;f++){const h=c[f],g=o[h];g>u&&(u=g);const w=t[h+1];let p=-1;for(let m=t[h];m<w;m++){const y=r[m],b=y===h||y===p;if(p=y,b)continue;const v=o[y];if(v>g){const A=l[y],E=i[v],I=c[E];y!==I&&(c[A]=I,c[E]=y,l[y]=E,l[I]=A),i[v]++,o[y]=v-1}}}let d=null;return{coreness:o,maxCore:u,cores(){if(d===null){const f=new Uint32Array(u+1);for(let w=0;w<e;w++)f[o[w]]++;const h=[];for(let w=0;w<=u;w++)h.push(new Uint32Array(f[w]));const g=new Uint32Array(u+1);for(let w=0;w<e;w++){const p=o[w];h[p][g[p]++]=w}d=h}return d}}}function Sh(n,e={}){const t=n.nodeCount,r=e.alpha??.1,o=e.beta??1,s=e.maxIterations??100,i=e.tolerance??1e-6,a=n.reverse(),c=e.weighted===!0?a.weights:null;let l=new Float64Array(t).fill(o),u=new Float64Array(t),d=0,f=!1;for(;d<s&&!f;d++){let h=0;for(let g=0;g<t;g++){let w=0;const p=a.rowPtr[g+1];for(let y=a.rowPtr[g];y<p;y++)w+=l[a.colIdx[y]]*(c===null?1:c[y]);u[g]=r*w+o;const m=Math.abs(u[g]-l[g]);m>h&&(h=m)}[l,u]=[u,l],f=h<i}if(e.normalized!==!1){let h=1/0,g=-1/0;for(let p=0;p<t;p++)l[p]<h&&(h=l[p]),l[p]>g&&(g=l[p]);const w=g-h;if(w>0)for(let p=0;p<t;p++)l[p]=(l[p]-h)/w}return{scores:l,iterations:d,converged:f}}const Y3=.01,X3=3;function Ph(n,e){const{nodeCount:t,rowPtr:r,colIdx:o,arcToEdge:s}=n,i=new Float64Array(n.arcCount),a=new Float64Array(t);for(let c=0;c<t;c++)for(let l=r[c],u=r[c+1];l<u;l++){const d=e[s[l]];i[l]=d,a[c]+=o[l]===c?2*d:d}return{s:n,edgeW:e,arcW:i,deg:a}}function xh(n,e){const t=new Uint32Array(n);for(let r=0;r<n;r++)t[r]=r;for(let r=n-1;r>=1;r--){const o=Math.floor(e()*(r+1)),s=t[r];t[r]=t[o],t[o]=s}return t}function Q3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c),f=new Uint32Array(c);for(let I=0;I<c;I++)d[e[I]]+=a[I],f[e[I]]++;const h=[];for(let I=c-1;I>=0;I--)f[I]===0&&h.push(I);const g=new Float64Array(c),w=new Int32Array(c).fill(-1),p=new Uint32Array(c),m=c+1,y=new Uint32Array(m);y.set(xh(c,t));const b=new Uint8Array(c).fill(1);let v=0,A=c,E=0;for(;v!==A;){const I=y[v];v=v+1===m?0:v+1,b[I]=0,E++;const k=e[I],N=a[I];d[k]-=N,f[k]--;let C=0;for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];if(F===I)continue;const M=e[F];w[M]!==E&&(w[M]=E,g[M]=0,p[C++]=M),g[M]+=i[$]}let O=k,T=(w[k]===E?g[k]:0)-r*N*d[k]/o;for(let $=0;$<C;$++){const L=p[$],F=g[L]-r*N*d[L]/o;L!==k&&F>T&&(T=F,O=L)}if(f[k]>0&&T<0&&(O=h[h.length-1]),O!==k&&f[O]===0&&h.pop(),d[O]+=N,f[O]++,O!==k){e[I]=O,f[k]===0&&h.push(k);for(let $=l[I],L=l[I+1];$<L;$++){const F=u[$];b[F]===0&&e[F]!==O&&(b[F]=1,y[A]=F,A=A+1===m?0:A+1)}}}}function J3(n,e,t,r,o){const{s,arcW:i,deg:a}=n,{nodeCount:c,rowPtr:l,colIdx:u}=s,d=new Float64Array(c);for(let v=0;v<c;v++)d[e[v]]+=a[v];const f=new Uint32Array(c),h=new Float64Array(c),g=new Uint32Array(c),w=new Float64Array(c);for(let v=0;v<c;v++){f[v]=v,h[v]=a[v],g[v]=1;for(let A=l[v],E=l[v+1];A<E;A++){const I=u[A];I!==v&&e[I]===e[v]&&(w[v]+=i[A])}}const p=new Float64Array(c),m=new Int32Array(c).fill(-1),y=new Uint32Array(c),b=xh(c,t);for(let v=0;v<c;v++){const A=b[v],E=e[A],I=a[A];if(g[A]!==1||w[A]<r*I*(d[E]-I)/o)continue;let k=0;for(let M=l[A],R=l[A+1];M<R;M++){const D=u[M];if(D===A||e[D]!==E)continue;const U=f[D];m[U]!==A&&(m[U]=A,p[U]=0,y[k++]=U),p[U]+=i[M]}const N=M=>p[M]-r*I*h[M]/o;let C=-1/0,O=0;for(let M=0;M<k;M++){const R=y[M],D=N(R);D>=0&&w[R]>=r*h[R]*(d[E]-h[R])/o&&(y[O++]=R,C=Math.max(C,D))}if(O===0)continue;const T=M=>Qr((N(M)-C)*2/o/Y3);let $=0;for(let M=0;M<O;M++)$+=T(y[M]);let L=t()*$,F=y[O-1];for(let M=0;M<O-1;M++)if(L-=T(y[M]),L<0){F=y[M];break}f[A]=F,g[A]=0,g[F]++,h[F]+=I,w[F]+=w[A]-2*p[F]}return f}function Z3(n,e,t,r,o){const s=n.s.nodeCount,i=new Uint32Array(s);for(let d=0;d<s;d++)i[d]=d;let a=n,c=e.slice(),l=0;for(;;){Q3(a,c,t,r,o),l++;const d=Je(c);if(d.count===a.s.nodeCount)break;let f=J3(a,d.labels,t,r,o);Je(f).count===a.s.nodeCount&&(f=d.labels);const h=a.s.contract(f),{nodeRemap:g,edgeRemap:w}=h,p=h.snapshot,m=new Float64Array(p.edgeCount);for(let b=0;b<a.edgeW.length;b++)m[w===null?b:w[b]]+=a.edgeW[b];const y=new Uint32Array(p.nodeCount);for(let b=0;b<a.s.nodeCount;b++)y[g===null?b:g[b]]=d.labels[b];if(g!==null)for(let b=0;b<s;b++)i[b]=g[i[b]];c=Je(y).labels,a=Ph(p,m)}const u=new Uint32Array(s);for(let d=0;d<s;d++)u[d]=c[i[d]];return{comm:u,levels:l}}function eE(n){const e=li(n)??n.edgeList().weights,t=e===null?new Float64Array(n.edgeCount).fill(1):Float64Array.from(e);for(let r=0;r<t.length;r++){const o=t[r];if(!(o>=0)||o===1/0)throw Q(new RangeError(`edge ${r} has weight ${o}; Leiden needs finite, non-negative weights`),"E_BAD_WEIGHT")}return t}function Ch(n,e={}){if(n.directed)throw Q(new Error("Leiden requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.randomSeed??42,o=e.maxIterations??100,s=e.threshold??1e-7;if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const i=n.nodeCount,a=Ph(n,eE(n));let c=0;for(let w=0;w<i;w++)c+=a.deg[w];let l=new Uint32Array(i);for(let w=0;w<i;w++)l[w]=w;if(c===0)return{...We(l,i),modularity:0,iterations:0};const u=w=>xc(n,w,{resolution:t,weights:a.arcW}),d=no(r);let f=u(l),h=0,g=0;for(let w=0;w<o&&g<X3;w++){const{comm:p,levels:m}=Z3(a,l,d,t,c);h+=m;const y=Je(p).labels,b=u(y);b>f?(g=b-f<=s?g+1:0,l=y,f=b):g++}return{...We(l,Je(l).count),modularity:f,iterations:h}}const Nh=2**36;function tE(n){return n>1?Math.round(Nh/Ge(n))/Nh:n===1?1:0}function Th(n,e){const t=n.rowPtr[e],r=n.rowPtr[e+1];let o=0;for(let s=t;s<r;s++)(s===t||n.colIdx[s]!==n.colIdx[s-1])&&o++;return o}function Oh(n,e){const t=n.directed&&!e?n.reverse():void 0;return r=>tE(Th(n,r)+(t===void 0?0:Th(t,r)))}function ro(n,e,t){const r=e.directed===!0?n.reverse():n,o=n.nodeCount;return(s,i)=>s<o&&i<o?Zf(n,r,s,i,t):0}function ui(n,e){const t=Oh(n,e.directed===!0),r=Float64Array.from({length:n.nodeCount},(o,s)=>t(s));return ro(n,e,o=>r[o])}function $h(n,e,t,r){const o=Array.from(t,(s,i)=>i).sort((s,i)=>t[i]-t[s]).slice(0,r);return{sources:Uint32Array.from(o,s=>n[s]),targets:Uint32Array.from(o,s=>e[s]),scores:Float64Array.from(o,s=>t[s])}}function nE(n,e,t,r,o,s,i){n.push(r),e.push(o),t.push(s),i&&(n.push(o),e.push(r),t.push(s))}function Rh(n,e,t){const r=[],o=[],s=[],i=e.directed!==!0&&e.uniquePairs!==!0;for(let c=0;c<n.nodeCount;c++)for(let l=c+1;l<n.nodeCount;l++){if(e.includeExisting!==!0&&n.hasArc(c,l))continue;const u=t(c,l);u>0&&nE(r,o,s,c,l,u,i)}const{topK:a}=e;return $h(r,o,s,a!==void 0&&a>0?a:s.length)}function oo(n,e){return Float64Array.from(n.sources,(t,r)=>e(t,n.targets[r]))}function Dh(n,e,t,r){const o=n.nodeCount,s=[],i=[],a=[];if(e<o){const c=t.candidates===void 0?Array.from({length:o},(l,u)=>u):ss(n,t.candidates);for(let l=0;l<c.length;l++){const u=c[l];if(u===e||t.includeExisting!==!0&&u<o&&n.hasArc(e,u))continue;const d=r(e,u);d>0&&(s.push(e),i.push(u),a.push(d))}}return $h(s,i,a,t.topK??10)}function Lh(n,e){const t=[...n,...e],r=Array.from(t,(u,d)=>d).sort((u,d)=>t[d]-t[u]);let o=0,s=0,i=0,a=0,c=0,l=0;for(const u of r){u<n.length?o++:(l+=o,s++);const d=o/(o+s),f=o/n.length,h=d+f>0?2*(d*f)/(d+f):0;h>i&&(i=h,a=d,c=f)}return l=o>0&&s>0?l/(o*s):.5,{precision:a,recall:c,f1Score:i,auc:l}}function Mh(n,e={}){return Rh(n,e,ro(n,e))}function rE(n,e,t={}){return oo(e,ro(n,t))}function oE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ro(n,t))}function Uh(n,e,t,r={}){const o=ro(n,r);return Lh(oo(e,o),oo(t,o))}function sE(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);return ro(n,r,Oh(n,r.directed===!0))(o,s)}function Fh(n,e={}){return Rh(n,e,ui(n,e))}function iE(n,e,t={}){return oo(e,ui(n,t))}function aE(n,e,t={}){const r=xe(n,e);return Dh(n,r,t,ui(n,t))}function Bh(n,e,t,r={}){const o=ui(n,r);return Lh(oo(e,o),oo(t,o))}function cE(n){const e=n.nodeCount,t=new Uint32Array(e+1);for(let r=0;r<e;r++){let o=0;const s=n.rowPtr[r+1];for(let i=n.rowPtr[r];i<s;i++)n.colIdx[i]!==r&&o++;t[r+1]=t[r]+o}return t}function lE(n){const e=n.nodeCount,t=cE(n),r=t[e],o=new Uint32Array(r),s=new Float64Array(r),i=new Float64Array(e),a=new Float64Array(e);let c=0;for(let l=0;l<e;l++){let u=0;const d=n.rowPtr[l+1];for(let f=n.rowPtr[l];f<d;f++){const h=n.colIdx[f],g=n.weights===null?1:n.weights[f];h===l?i[l]+=g:(o[c]=h,s[c]=g,c++,u+=g)}a[l]=u+2*i[l]}return{n:e,rowPtr:t,colIdx:o,w:s,loop:i,deg:a}}function zh(n,e,t,r,o){const s=new Float64Array(t),i=new Float64Array(t);for(let c=0;c<n.n;c++){const l=e[c];i[l]+=n.deg[c],s[l]+=2*n.loop[c];const u=n.rowPtr[c+1];for(let d=n.rowPtr[c];d<u;d++)e[n.colIdx[d]]===l&&(s[l]+=n.w[d])}let a=0;for(let c=0;c<t;c++){const l=i[c]/o;a+=s[c]/o-r*l*l}return a}function uE(n,e,t,r,o){const{n:s}=n,i=new Float64Array(s);for(let b=0;b<s;b++)e[b]=b,i[b]=n.deg[b];const a=new Float64Array(s),c=new Int32Array(s).fill(-1),l=new Uint32Array(s),u=s+1,d=new Uint32Array(u),f=new Uint8Array(s);let h=0,g=s;for(let b=0;b<s;b++)d[b]=b,f[b]=1;let w=0,p=0;const m=o*s;let y=!1;for(;h!==g&&p<m;){const b=d[h];h=h+1===u?0:h+1,f[b]=0,p++;const v=e[b],A=n.deg[b];i[v]-=A,w++;let E=0;const I=n.rowPtr[b+1];for(let C=n.rowPtr[b];C<I;C++){const O=e[n.colIdx[C]];c[O]!==w&&(c[O]=w,a[O]=0,l[E++]=O),a[O]+=n.w[C]}let k=v,N=(c[v]===w?a[v]:0)-t*A*i[v]/r;for(let C=0;C<E;C++){const O=l[C];if(O===v)continue;const T=a[O]-t*A*i[O]/r;T>N&&(N=T,k=O)}if(i[k]+=A,k!==v){e[b]=k,y=!0;for(let C=n.rowPtr[b];C<I;C++){const O=n.colIdx[C];f[O]===0&&e[O]!==k&&(f[O]=1,d[g]=O,g=g+1===u?0:g+1)}}}return y}function dE(n,e,t){const r=new Uint32Array(t+1);for(let i=0;i<n;i++)r[e[i]+1]++;for(let i=0;i<t;i++)r[i+1]+=r[i];const o=new Uint32Array(n),s=r.slice(0,t);for(let i=0;i<n;i++)o[s[e[i]]++]=i;return{start:r,members:o}}function fE(n,e,t,r,o,s){let i=0;for(let a=0;a<e;a++){const c=n[a];r[s+a]=c,o[s+a]=t[c],i+=t[c]}return i}function hE(n,e,t){const{start:r,members:o}=dE(n.n,e,t),s=new Uint32Array(t+1),i=new Uint32Array(n.colIdx.length),a=new Float64Array(n.colIdx.length),c=new Float64Array(t),l=new Float64Array(t),u=new Float64Array(t),d=new Int32Array(t).fill(-1),f=new Uint32Array(t);let h=0;for(let g=0;g<t;g++){s[g]=h;let w=0,p=0;for(let y=r[g];y<r[g+1];y++){const b=o[y];c[g]+=n.loop[b];const v=n.rowPtr[b+1];for(let A=n.rowPtr[b];A<v;A++){const E=e[n.colIdx[A]];if(E===g){w+=n.w[A];continue}d[E]!==g&&(d[E]=g,u[E]=0,f[p++]=E),u[E]+=n.w[A]}}c[g]+=w/2;const m=fE(f,p,u,i,a,h);h+=p,l[g]=m+2*c[g]}return s[t]=h,{n:t,rowPtr:s,colIdx:i.subarray(0,h),w:a.subarray(0,h),loop:c,deg:l}}function Gh(n,e={}){if(n.directed)throw Q(new Error("Louvain requires an undirected graph. Pass s.toUndirected().snapshot."),"E_NEEDS_UNDIRECTED");const t=e.resolution??1,r=e.maxIterations??100,o=e.tolerance??1e-6,s=n.nodeCount,i=new Uint32Array(s);for(let f=0;f<s;f++)i[f]=f;let a=lE(n),c=0;for(let f=0;f<s;f++)c+=a.deg[f];if(c===0)return{...We(i,s),modularity:0,iterations:0};let l=zh(a,i,s,t,c),u=0;for(let f=0;f<r;f++){const h=new Uint32Array(a.n);if(!uE(a,h,t,c,r))break;const g=Je(h),{count:w}=g,p=g.labels,m=zh(a,p,w,t,c);for(let b=0;b<s;b++)i[b]=p[i[b]];u=f+1;const y=m-l;if(l=m,y<o||w===a.n)break;a=hE(a,p,w)}const d=Je(i);return{...We(d.labels,d.count),modularity:l,iterations:u}}function Cc(n){for(let e=0;e+1<n.ptr.length;e++){let t=0;for(let r=n.ptr[e];r<n.ptr[e+1];r++)t+=n.val[r];if(t>0)for(let r=n.ptr[e];r<n.ptr[e+1];r++)n.val[r]/=t}}function gE(n,e,t,r){const o=t.length,s=new Uint32Array(o+1),i=[],a=[],c=[];for(let l=0;l<o;l++){c.length=0;for(let u=e.ptr[l];u<e.ptr[l+1];u++){const d=e.row[u],f=e.val[u];for(let h=n.ptr[d];h<n.ptr[d+1];h++){const g=n.row[h];r[g]===0&&(r[g]=1,c.push(g)),t[g]+=n.val[h]*f}}c.sort((u,d)=>u-d);for(const u of c)i.push(u),a.push(t[u]),t[u]=0,r[u]=0;s[l+1]=i.length}return{ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)}}function wE(n,e,t){const r={ptr:n.ptr,row:n.row,val:n.val.map(l=>JA(l,e))};Cc(r);const o=n.ptr.length-1,s=new Uint32Array(o+1),i=[],a=[];for(let l=0;l<o;l++){for(let u=r.ptr[l];u<r.ptr[l+1];u++)r.val[u]>=t&&(i.push(r.row[u]),a.push(r.val[u]));s[l+1]=i.length}const c={ptr:s,row:Uint32Array.from(i),val:Float64Array.from(a)};return Cc(c),c}function pE(n,e,t){for(let r=0;r+1<n.ptr.length;r++){let o=n.ptr[r],s=e.ptr[r];const i=n.ptr[r+1],a=e.ptr[r+1];for(;o<i||s<a;){let c;if(s>=a||o<i&&n.row[o]<e.row[s]?c=n.val[o++]:o>=i||e.row[s]<n.row[o]?c=e.val[s++]:c=n.val[o++]-e.val[s++],Math.abs(c)>t)return!1}}return!0}function mE(n,e){const t=n===null?1:n[e];if(!(t>=0)||t===1/0)throw Q(new RangeError(`arc ${e} has weight ${t}; Markov clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");return t}function yE(n,e,t){const r=n.nodeCount,o=new Uint32Array(r+1);for(let h=0;h<n.arcCount;h++)o[n.colIdx[h]+1]++;if(t)for(let h=0;h<r;h++)o[h+1]++;for(let h=0;h<r;h++)o[h+1]+=o[h];const s=o.slice(0,r),i=new Uint32Array(o[r]),a=new Float64Array(o[r]),c=(h,g,w,p)=>{const m=s[g]-1;m>=o[g]&&i[m]===h?a[m]=p?w:a[m]+w:(i[s[g]]=h,a[s[g]++]=w)};for(let h=0;h<r;h++){for(let g=n.rowPtr[h];g<n.rowPtr[h+1];g++){const w=n.colIdx[g];c(h,w,mE(e,g),!1)}t&&c(h,h,1,!0)}const l=new Uint32Array(r+1),u=[],d=[];for(let h=0;h<r;h++){for(let g=o[h];g<s[h];g++)u.push(i[g]),d.push(a[g]);l[h+1]=u.length}const f={ptr:l,row:Uint32Array.from(u),val:Float64Array.from(d)};return Cc(f),f}function bE(n,e={}){const t=e.expansion??2,r=e.inflation??2,o=e.maxIterations??100,s=e.tolerance??1e-6,i=e.pruningThreshold??1e-5;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`expansion must be an integer of at least 1, got ${t}`),"E_BAD_OPTION");if(!(r>0)||r===1/0)throw Q(new RangeError(`inflation must be finite and above 0, got ${r}`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0)throw Q(new RangeError(`maxIterations must be a non-negative integer, got ${o}`),"E_BAD_OPTION");if(!(s>=0)||!(i>=0))throw Q(new RangeError("tolerance and pruningThreshold must be non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;let l=yE(n,a,e.selfLoops??!0);const u=new Float64Array(c),d=new Uint8Array(c);let f=c===0,h=0;for(;!f&&h<o;){let b=l;for(let A=1;A<t;A++)b=gE(b,l,u,d);const v=wE(b,r,i);h++,f=pE(l,v,s),l=v}const g=[],w=new Int32Array(c).fill(-1);for(let b=0;b<c;b++){let v=0;for(let A=l.ptr[b];A<l.ptr[b+1];A++)l.row[A]===b&&l.val[A]>0&&g.push(b),l.val[A]>v&&(v=l.val[A],w[b]=l.row[A])}const p=new Uint32Array(c),m=new Map;for(let b=0;b<c;b++){const v=w[b];if(v>=0){let A=m.get(v);A===void 0&&(A=m.size,m.set(v,A)),p[b]=A}}let y=m.size;for(let b=0;b<c;b++)w[b]<0&&(p[b]=y++);return{...We(p,y),attractors:Uint32Array.from(g),iterations:h,converged:f}}function Wh(n,e){return e instanceof Uint32Array?e:Df(n,e)}function Vh(n,e){const t=n.directed&&e.arcs!=="out"?[n,n.reverse()]:[n];if(e.left!==void 0&&e.right!==void 0)return{left:Wh(n,e.left),right:Wh(n,e.right),views:t};const{sides:r}=Yf(n,{arcs:e.arcs});if(r===null)throw Q(new Error("Graph is not bipartite"),"E_NOT_BIPARTITE");const o=At(n.nodeCount);for(let i=0;i<o.length;i++)o[i]=~r[i];const s=n.nodeCount%32;return s!==0&&(o[o.length-1]&=(1<<s)-1),{left:o,right:r,views:t}}function vE(n,e,t){const r=new Uint32Array(e+1),o=new Uint32Array(t+1);for(const{rowPtr:u,arcToEdge:d}of n){for(let f=0;f<e;f++)r[f+1]+=u[f+1]-u[f];for(const f of d)o[f+1]++}for(let u=0;u<e;u++)r[u+1]+=r[u];for(let u=0;u<t;u++)o[u+1]+=o[u];const s=r[e],i=new Uint32Array(s),a=new Uint32Array(s);for(const{rowPtr:u,colIdx:d,arcToEdge:f}of n)for(let h=0;h<e;h++)for(let g=u[h];g<u[h+1];g++){const w=o[f[g]]++;i[w]=h,a[w]=d[g]}const c=r.slice(0,e),l=new Uint32Array(s);for(let u=0;u<s;u++)l[c[i[u]]++]=a[u];return{start:r,nbr:l}}function jh(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,{start:i,nbr:a}=vE(o,s,n.edgeCount),c=new Uint32Array(s),l=new Uint8Array(s);let u=0;for(let y=0;y<s;y++){if(l[y]===1)continue;l[y]=1;let b=u;for(c[u++]=y;b<u;){const v=c[b++];for(let A=i[v];A<i[v+1];A++)l[a[A]]===0&&(l[a[A]]=1,c[u++]=a[A])}}const d=new Uint32Array(s).fill(x),f=new Uint32Array(s).fill(x),h=new Uint32Array(s),g=new Uint32Array(s),w=new Uint32Array(s),p=new Uint32Array(s);let m=0;for(let y=0;y<s;y++){const b=c[y];if(!_e(t,b))continue;const v=y+1;let A=0;g[A++]=b,w[b]=i[b];let E=x;e:for(;A>0;){const I=g[A-1];for(;w[I]<i[I+1];){const k=a[w[I]++];if(h[k]===v||!_e(r,k))continue;h[k]=v;const N=f[k];if(N===x){E=k;break e}p[I]=k,g[A++]=N,w[N]=i[N];continue e}A--}if(E!==x){for(let I=A-1;I>=0;I--){const k=g[I],N=I===A-1?E:p[k];d[k]=N,f[N]=k}m++}}return{matching:d,size:m}}function AE(n,e={}){const{left:t,right:r,views:o}=Vh(n,e),{nodeCount:s}=n,i=new Uint32Array(s).fill(x),a=new Uint8Array(s);let c=0;for(let l=0;l<s;l++)if(_e(t,l))e:for(const{rowPtr:u,colIdx:d}of o){const f=u[l+1];for(let h=u[l];h<f;h++){const g=d[h];if(a[g]===0&&_e(r,g)){a[g]=1,i[l]=g,c++;break e}}}return{matching:i,size:c}}function qh(n,e={}){const t=n.nodeCount,r=Ac(n,e.weights);if(t<2){const y=At(t,!0);return{...to(y,t),cutValue:0,side:y,cutEdges:new Uint32Array(0)}}const{src:o,dst:s}=n.edgeList(),i=new Uint32Array(t+1);for(let y=0;y<n.edgeCount;y++)i[o[y]+1]++,i[s[y]+1]++;for(let y=0;y<t;y++)i[y+1]+=i[y];const a=i.slice(0,t),c=new Uint32Array(i[t]),l=new Float64Array(i[t]);for(let y=0;y<n.edgeCount;y++)c[a[o[y]]]=s[y],l[a[o[y]]++]=r[y],c[a[s[y]]]=o[y],l[a[s[y]]++]=r[y];const u=new Uint32Array(t),d=new Uint32Array(t).fill(x),f=new Uint32Array(t);for(let y=0;y<t;y++)u[y]=y,f[y]=y;const h=new Float64Array(t),g=new Uint8Array(t),w=new sh(t);let p=1/0,m=At(t);for(let y=t;y>1;y--){let b=x;for(let E=0;E<t;E++)u[E]===E&&(g[E]=0,h[E]=0,b===x?b=E:w.push(E,0));let v=x,A=b;for(;;){g[A]=1;for(let E=A;E!==x;E=d[E])for(let I=i[E];I<i[E+1];I++){const k=u[c[I]];g[k]===0&&(h[k]+=l[I],w.pushOrIncrease(k,h[k]))}if(w.isEmpty())break;v=A,A=w.pop()}if(h[A]<p){p=h[A],m=At(t);for(let E=A;E!==x;E=d[E])pn(m,E,!0)}for(let E=A;E!==x;E=d[E])u[E]=v;d[f[v]]=A,f[v]=f[A]}return{...to(m,t),cutValue:p,side:m,cutEdges:Ec(n,m,!1,r,!1)}}function Hh(n,e={}){const t=e.iterations??100,r=e.randomSeed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`iterations must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!Number.isInteger(r))throw Q(new RangeError(`randomSeed must be a finite integer, got ${r}`),"E_BAD_OPTION");const o=n.nodeCount,s=Ac(n,e.weights);if(o<2){const f=At(o);return{...to(f,o),cutValue:0,side:f,cutEdges:new Uint32Array(0)}}const{src:i,dst:a}=n.edgeList(),c=no(r),l=new Uint32Array(n.edgeCount);let u=1/0,d=At(o);for(let f=0;f<t;f++){for(let m=0;m<l.length;m++)l[m]=m;for(let m=l.length-1;m>0;m--){const y=Math.floor(c()*(m+1)),b=l[m];l[m]=l[y],l[y]=b}const h=new eo(o);let g=o;for(let m=0;m<l.length&&g>2;m++)h.union(i[l[m]],a[l[m]])&&g--;const w=h.find(0);let p=0;for(let m=0;m<n.edgeCount;m++)h.find(i[m])===w!=(h.find(a[m])===w)&&(p+=s[m]);if(p<u){u=p,d=At(o);for(let m=0;m<o;m++)pn(d,m,h.find(m)===w)}}return{...to(d,o),cutValue:u,side:d,cutEdges:Ec(n,d,!1,s,!1)}}function Kh(n,e={}){const t=n.edgeList(),r=n.edgeCount,o=new Float64Array(r);if(e.weights!==void 0)for(let u=0;u<r;u++)o[u]=e.weights[t.arc[u]];else if(t.weights!==null)for(let u=0;u<r;u++)o[u]=t.weights[u];else o.fill(1);const s=new Array(r);for(let u=0;u<r;u++)s[u]=u;s.sort((u,d)=>o[u]-o[d]||u-d);const i=new eo(n.nodeCount),a=new Uint32Array(Math.max(n.nodeCount-1,0));let c=0,l=0;for(const u of s)i.union(t.src[u],t.dst[u])&&(a[c++]=u,l+=o[u]);return{edges:a.subarray(0,c),totalWeight:l}}function Yh(n,e={}){if(n.directed)throw Q(new Error("Prim's algorithm requires an undirected graph"),"E_NEEDS_UNDIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=e.weights??n.weights,i=new Float64Array(t).fill(1/0),a=new Uint32Array(t).fill(x),c=new Uint8Array(t),l=new Yn(t),u=new Uint32Array(Math.max(t-1,0));let d=0,f=0;const h=g=>{for(l.push(g,0);!l.isEmpty();){const w=l.pop();c[w]=1,a[w]!==x&&(u[d++]=n.arcToEdge[a[w]],f+=i[w]);for(let p=r[w];p<r[w+1];p++){const m=o[p],y=s===null?1:s[p];c[m]===0&&y<i[m]&&(i[m]=y,a[m]=p,l.pushOrDecrease(m,y))}}};if(t>0&&h(e.start===void 0?0:xe(n,e.start)),e.forest===!0)for(let g=0;g<t;g++)c[g]===0&&h(g);else if(d<t-1)throw Q(new Error("Graph is not connected"),"E_NOT_CONNECTED");return{edges:u.subarray(0,d),totalWeight:f,predArc:a}}function Xh(n,e={}){return Jh(n,null,e)}function Qh(n,e,t={}){return Jh(n,eg(e,n.nodeCount,"personalization"),t)}function Jh(n,e,t){const r=n.nodeCount,o=t.dampingFactor??.85,s=t.maxIterations??100,i=t.tolerance??1e-6,a=t.convergenceNorm==="max";if(r===0)return{scores:new Float64Array(0),iterations:0,converged:!0};const c=n.reverse(),l=t.weighted===!0&&c.weights!==null,u=l?n.edges.byRole("weight"):null,d=u?.dtype==="f64"?u.data:null;let f=l?c.weights:null,h=l?n.weightedOutDegree():n.outDegree();d!==null&&(f=Zh(d,c.arcToEdge),h=EE(n,Zh(d,n.arcToEdge)));let g=(t.initialRanks===void 0?null:eg(t.initialRanks,r,"initialRanks"))??new Float64Array(r).fill(t.initialRanks===void 0?1/r:0),w=new Float64Array(r),p=0,m=!1;for(;p<s&&!m;p++){let y=0;for(let A=0;A<r;A++)h[A]===0&&(y+=g[A]);const b=1-o+o*y*(e===null?1:1/r);let v=0;for(let A=0;A<r;A++){let E=0;const I=c.rowPtr[A+1];for(let N=c.rowPtr[A];N<I;N++){const C=c.colIdx[N],O=h[C];O>0&&(E+=g[C]*(f===null?1:f[N])/O)}w[A]=b*(e===null?1/r:e[A])+o*E;const k=Math.abs(w[A]-g[A]);v=a?Math.max(v,k):v+k}[g,w]=[w,g],m=v<i}return{scores:g,iterations:p,converged:m}}function Zh(n,e){const t=new Float64Array(e.length);for(let r=0;r<t.length;r++)t[r]=n[e[r]];return t}function EE(n,e){const t=new Float64Array(n.nodeCount);for(let r=0;r<n.nodeCount;r++)for(let o=n.rowPtr[r];o<n.rowPtr[r+1];o++)t[r]+=e[o];return t}function eg(n,e,t){if(n.length!==e)throw Q(new Error(`PageRank: ${t} has ${String(n.length)} entries for ${String(e)} nodes`),"E_BAD_OPTION");let r=0;for(const s of n){if(!Number.isFinite(s)||s<0)throw Q(new Error(`PageRank: ${t} must be finite and non-negative, got ${String(s)}`),"E_BAD_OPTION");r+=s}if(r===0)return null;const o=new Float64Array(e);for(let s=0;s<e;s++)o[s]=n[s]/r;return o}const tg={distance:1/0,path:new Uint32Array(0),edges:new Uint32Array(0)};function _E(n,e,t,r={}){const o=xe(n,e),s=xe(n,t);if(o===s)return{distance:0,path:Uint32Array.of(o),edges:new Uint32Array(0)};const i=n.nodeCount,a=r.weights??n.weights;if(a?.some(C=>C<0)===!0)throw Q(new Error("Bidirectional Dijkstra does not support negative edge weights"),"E_BAD_WEIGHT");const c=n.reverse(),l=C=>a===null?1:a[C],u=new Float64Array(i).fill(1/0),d=new Float64Array(i).fill(1/0),f=new Uint32Array(i).fill(x),h=new Uint32Array(i).fill(x),g=new Uint32Array(i).fill(x),w=new Yn(i),p=new Yn(i);u[o]=0,d[s]=0,w.push(o,0),p.push(s,0);let m=1/0,y=x,b=x,v=x,A=0;for(;w.peekKey()+p.peekKey()<m;)if(w.peekKey()<=p.peekKey()){const C=w.pop();for(let O=n.rowPtr[C];O<n.rowPtr[C+1];O++){const T=n.colIdx[O],$=l(O),L=u[C]+$;L<u[T]&&(u[T]=L,f[T]=O,w.pushOrDecrease(T,L)),L+d[T]<m&&(m=L+d[T],[y,b,v,A]=[C,T,n.arcToEdge[O],$])}}else{const C=p.pop();for(let O=c.rowPtr[C];O<c.rowPtr[C+1];O++){const T=c.colIdx[O],$=l(c.fwdArc[O]),L=d[C]+$;L<d[T]&&(d[T]=L,h[T]=O,g[T]=C,p.pushOrDecrease(T,L)),u[T]+L<m&&(m=u[T]+L,[y,b,v,A]=[T,C,c.arcToEdge[O],$])}}if(y===x)return tg;const E=[],I=[],k=[];for(let C=y;C!==o;C=n.arcSource(f[C]))E.push(C),I.push(n.arcToEdge[f[C]]),k.push(l(f[C]));E.push(o),E.reverse(),I.reverse(),k.reverse(),I.push(v),k.push(A),E.push(b);for(let C=b;C!==s;C=g[C])I.push(c.arcToEdge[h[C]]),k.push(l(c.fwdArc[h[C]])),E.push(g[C]);let N=0;for(const C of k)N+=C;return{distance:N,path:Uint32Array.from(E),edges:Uint32Array.from(I)}}function IE(n,e,t,r,o){const{gScore:s,fScore:i,predArc:a,closed:c,heap:l}=o;for(let u=n.rowPtr[e];u<n.rowPtr[e+1];u++){const d=n.colIdx[u];if(c[d]===1)continue;const f=s[e]+(t===null?1:t[u]);f<s[d]&&(s[d]=f,i[d]=f+r(d),a[d]=u,l.pushOrDecrease(d,i[d]))}}function kE(n,e,t,r,o={}){const s=xe(n,e),i=xe(n,t),a=n.nodeCount;if(!(i>=0&&i<a))throw Q(new RangeError(`Target index ${String(i)} is outside the graph's ${String(a)} nodes`),"E_BAD_NODE");const c=o.weights??n.weights,l=new Float64Array(a).fill(1/0),u=new Float64Array(a).fill(1/0),d=new Uint32Array(a).fill(x),f=new Uint8Array(a),h=[],g=new Yn(a);for(l[s]=0,u[s]=r(s,i),g.push(s,u[s]);!g.isEmpty();){const m=g.pop();if(m===i)break;f[m]=1,h.push(m),IE(n,m,c,y=>r(y,i),{gScore:l,fScore:u,predArc:d,closed:f,heap:g})}const w={gScore:l,fScore:u,visited:Uint32Array.from(h)};if(l[i]===1/0)return{...tg,...w};const p=Jr(n,d,s,i);return{distance:l[i],path:p,edges:Zr(n,d,s,i),...w}}function Nc(n,e={}){const{labels:t,count:r}=SE(n,e);return We(t,r)}function SE(n,e={}){if(!n.directed)throw Q(new Error("Strongly connected components require a directed graph. Use connectedComponents for an undirected one."),"E_NEEDS_DIRECTED");const{nodeCount:t,rowPtr:r,colIdx:o}=n,s=ci(n,e.arcOrder),i=new Uint32Array(t).fill(x),a=new Uint32Array(t),c=new Uint32Array(t),l=new Uint8Array(t),u=new Uint32Array(t),d=new Uint32Array(t),f=new Uint32Array(t),h=new Uint32Array(t);let g=0,w=0,p=0,m=0,y=0;const b=v=>{i[v]=w,a[v]=w,w++,c[v]=r[v],d[m++]=v,l[v]=1,u[y++]=v};for(let v=0;v<t;v++)if(i[v]===x)for(b(v);y>0;){const A=u[y-1];if(c[A]<r[A+1]){const E=c[A]++,I=o[s===null?E:s[E]];i[I]===x?b(I):l[I]===1&&i[I]<a[A]&&(a[A]=i[I]);continue}if(y--,a[A]===i[A]){let E;do E=d[--m],l[E]=0,f[E]=p,h[g++]=E;while(E!==A);p++}y>0&&a[A]<a[u[y-1]]&&(a[u[y-1]]=a[A])}return{labels:f,count:p,popped:h}}function PE(n,e={}){const t=Nc(n,e),r=n.contract(t.labels,{selfLoops:"drop",parallel:"merge",weights:"first"});return{components:t,condensed:r}}const xE=1e-11,ng=3e3;function CE(n,e){const t=n.nodeCount,r=[{view:n,arcOf:l=>l}];if(n.directed){const l=n.reverse();r.push({view:l,arcOf:u=>l.fwdArc[u]})}const o=new Uint32Array(t+1);for(let l=0;l<t;l++){let u=0;for(const{view:d}of r)for(let f=d.rowPtr[l];f<d.rowPtr[l+1];f++)u+=d.colIdx[f]===l?0:1;o[l+1]=o[l]+u}const s=new Uint32Array(o[t]),i=new Float64Array(o[t]),a=new Float64Array(t);let c=0;for(let l=0;l<t;l++)for(const{view:u,arcOf:d}of r)for(let f=u.rowPtr[l];f<u.rowPtr[l+1];f++){const h=e===null?1:e[d(f)];if(!(h>=0)||h===1/0)throw Q(new RangeError(`an arc has weight ${h}; spectral clustering needs finite, non-negative weights`),"E_BAD_WEIGHT");u.colIdx[f]!==l&&(s[c]=u.colIdx[f],i[c++]=h,a[l]+=h)}return{rowPtr:o,colIdx:s,w:i,degree:a}}function rg(n,e){for(let t=0;t<n.length;t++){const r=n[t];for(let o=0;;o++){for(let i=0;i<2;i++)for(let a=0;a<t;a++){const c=n[a];let l=0;for(let u=0;u<r.length;u++)l+=c[u]*r[u];for(let u=0;u<r.length;u++)r[u]-=l*c[u]}let s=0;for(let i=0;i<r.length;i++)s+=r[i]*r[i];if(s=Math.sqrt(s),s>1e-10||o===3){for(let i=0;i<r.length;i++)r[i]=s>0?r[i]/s:0;break}for(let i=0;i<r.length;i++)r[i]=e()-.5}}}function NE(n,e){const t=new Float64Array(e*e);for(let r=0;r<e;r++)t[r*e+r]=1;for(let r=0;r<100;r++){let o=0;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)o+=n[s*e+i]*n[s*e+i];if(o<1e-30)break;for(let s=0;s<e;s++)for(let i=s+1;i<e;i++){const a=n[s*e+i];if(a===0)continue;const c=(n[i*e+i]-n[s*e+s])/(2*a),l=Math.sign(c||1)/(Math.abs(c)+Math.sqrt(c*c+1)),u=1/Math.sqrt(l*l+1),d=l*u;for(let f=0;f<e;f++){const h=n[f*e+s],g=n[f*e+i];n[f*e+s]=u*h-d*g,n[f*e+i]=d*h+u*g}for(let f=0;f<e;f++){const h=n[s*e+f],g=n[i*e+f];n[s*e+f]=u*h-d*g,n[i*e+f]=d*h+u*g}for(let f=0;f<e;f++){const h=t[f*e+s],g=t[f*e+i];t[f*e+s]=u*h-d*g,t[f*e+i]=d*h+u*g}}}return{values:Float64Array.from({length:e},(r,o)=>n[o*e+o]),vectors:t}}function TE(n,e,t){const r=n.length,o=new Float64Array(r*r);for(let s=0;s<r;s++)for(let i=s;i<r;i++){let a=0;for(let c=0;c<t;c++)a+=n[s][c]*e[i][c];o[s*r+i]=a,o[i*r+s]=a}return o}function OE(n,e,t,r,o){const s=Math.min(e,t+Math.max(t,8));let i=Array.from({length:s},()=>Float64Array.from({length:e},()=>o()-.5));rg(i,o);const a=new Float64Array(e),c=w=>(n(w,a),w.map((p,m)=>r*p-a[m]));let l=new Float64Array(s),u=[],d=new Float64Array(s*s),f=!1;for(let w=0;w<ng;w++){const p=i.map(c);if({values:l,vectors:d}=NE(TE(i,p,e),s),u=Array.from({length:s},(y,b)=>b).sort((y,b)=>l[b]-l[y]),f=u.slice(0,t).every(y=>{let b=0;for(let v=0;v<e;v++){let A=0;for(let E=0;E<s;E++)A+=d[E*s+y]*(p[E][v]-l[y]*i[E][v]);b+=A*A}return Math.sqrt(b)<=xE*r}),f||w===ng-1)break;i=p,rg(i,o)}const h=new Float64Array(t),g=[];for(let w=0;w<t;w++){const p=u[w];h[w]=Math.max(0,r-l[p]);const m=new Float64Array(e);for(let y=0;y<s;y++){const b=d[y*s+p];for(let v=0;v<e;v++)m[v]+=b*i[y][v]}g.push(m)}return{values:h,vectors:g,converged:f}}const $E=10;function RE(n,e,t,r,o){const s=new Float64Array(o*r),i=new Float64Array(o);for(let c=0;c<t;c++){i[e[c]]++;for(let l=0;l<r;l++)s[e[c]*r+l]+=n[c*r+l]}let a=0;for(let c=0;c<t;c++){const l=e[c];for(let u=0;u<r;u++){const d=n[c*r+u]-s[l*r+u]/i[l];a+=d*d}}return a}function DE(n,e,t,r,o,s,i){const a=(f,h,g)=>{let w=0;for(let p=0;p<t;p++){const m=n[f*t+p]-h[g*t+p];w+=m*m}return w},c=new Float64Array(r*t),l=new Float64Array(e).fill(1/0);let u=Math.floor(i()*e);for(let f=0;f<r;f++){c.set(n.subarray(u*t,u*t+t),f*t);let h=0;for(let w=0;w<e;w++)l[w]=Math.min(l[w],a(w,c,f)),h+=l[w];let g=i()*h;u=0;for(let w=0;w<e&&h>0;w++)if(g-=l[w],g<0){u=w;break}}const d=new Uint32Array(e);for(let f=0;f<o;f++){let h=f===0;for(let m=0;m<e;m++){let y=0,b=1/0;for(let v=0;v<r;v++){const A=a(m,c,v);A<b&&(b=A,y=v)}h||(h=d[m]!==y),d[m]=y}if(!h)break;const g=new Float64Array(r*t),w=new Float64Array(r);for(let m=0;m<e;m++){w[d[m]]++;for(let y=0;y<t;y++)g[d[m]*t+y]+=n[m*t+y]}let p=0;for(let m=0;m<r;m++){if(w[m]===0)continue;let y=0;for(let b=0;b<t;b++){const v=g[m*t+b]/w[m],A=v-c[m*t+b];y+=A*A,c[m*t+b]=v}p=Math.max(p,Math.sqrt(y))}if(p<s)break}return d}function LE(n,e){const{k:t}=e,r=e.laplacianType??"normalized",o=e.maxIterations??100,s=e.tolerance??1e-4,i=e.seed??42;if(!Number.isInteger(t)||t<1)throw Q(new RangeError(`k must be a positive integer, got ${t}`),"E_BAD_OPTION");if(!["unnormalized","normalized","randomWalk"].includes(r))throw Q(new RangeError(`unknown laplacianType "${r}"`),"E_BAD_OPTION");if(!Number.isInteger(o)||o<0||!(s>=0)||!Number.isInteger(i))throw Q(new RangeError("maxIterations and seed must be integers, maxIterations and tolerance non-negative"),"E_BAD_OPTION");const a=e.weights??n.weights;if(a!==null&&a.length!==n.arcCount)throw Q(new RangeError(`weights has ${a.length} entries; the snapshot has ${n.arcCount} arcs`),"E_BAD_OPTION");const c=n.nodeCount;if(t>=c){const A=Uint32Array.from({length:c},(E,I)=>I);return{...We(A,c),eigenvalues:new Float64Array(0),eigenvectors:[],converged:!0}}const l=CE(n,a),u=l.degree.map(A=>A>0?1/Math.sqrt(A):0),d=r!=="unnormalized",f=(A,E)=>{for(let I=0;I<c;I++){let k=0;for(let N=l.rowPtr[I];N<l.rowPtr[I+1];N++){const C=l.colIdx[N];k+=d?l.w[N]*u[C]*A[C]:l.w[N]*A[C]}d?E[I]=l.degree[I]>0?A[I]-u[I]*k:0:E[I]=l.degree[I]*A[I]-k}};let h=2;if(!d){h=1;for(let A=0;A<c;A++)for(let E=l.rowPtr[A];E<l.rowPtr[A+1];E++)h=Math.max(h,l.degree[A]+l.degree[l.colIdx[E]])}const g=no(i),w=OE(f,c,t,h,g);if(r==="randomWalk")for(const A of w.vectors)for(let E=0;E<c;E++)A[E]*=l.degree[E]>0?u[E]:1;const p=new Float64Array(c*t);for(let A=0;A<t;A++)for(let E=0;E<c;E++)p[E*t+A]=w.vectors[A][E];if(r==="normalized")for(let A=0;A<c;A++){const E=p.subarray(A*t,A*t+t),I=YA(...E);I>0&&E.forEach((k,N)=>E[N]=k/I)}let m=new Uint32Array(c),y=1/0;for(let A=0;A<$E;A++){const E=DE(p,c,t,t,o,s,g),I=RE(p,E,c,t,t);I<y&&(y=I,m=E)}const{labels:b,count:v}=Je(m);return{...We(b,v),eigenvalues:w.values,eigenvectors:w.vectors,converged:w.converged}}const ME=10;function di(n,e,t,r,o){let s=0;for(let i=0;i<o;i++){const a=n[e*o+i]-t[r*o+i];s+=a*a}return Math.sqrt(s)}function UE(n,e,t){const r=n.nodeCount,o=new Float64Array(r*t),s=n.directed?n.degree():n.outDegree();for(let i=0;i<r;i++){const a=s[i]/Math.max(1,r-1);for(let c=0;c<t;c++)o[i*t+c]=(e()-.5)*.1+a*.1}return o}function FE(n,e){let t=1/0;for(let r=0;r<n.centreCount;r++)t=Math.min(t,di(n.emb,e,n.centres,r,n.dim));return t}function BE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n;for(let a=0;a<r;a++)if(t-=e[a],t<=0){i.set(s.subarray(a*o,(a+1)*o),n.centreCount*o),n.centreCount++;return}}function zE(n,e,t){const{n:r,dim:o,emb:s,centres:i}=n,a=Math.floor(t()*r);i.set(s.subarray(a*o,(a+1)*o),0),n.centreCount=1;const c=new Float64Array(r);for(let l=1;l<e;l++){let u=0;for(let d=0;d<r;d++){const f=FE(n,d);c[d]=f*f,u+=f*f}BE(n,c,t()*u)}}function og(n){const{n:e,dim:t,emb:r,centres:o,centreCount:s,labels:i}=n;for(let a=0;a<e;a++){let c=0,l=1/0;for(let u=0;u<s;u++){const d=di(r,a,o,u,t);d<l&&(l=d,c=u)}i[a]=c}}function GE(n,e,t,r){const{n:o,dim:s,rowPtr:i,colIdx:a,emb:c}=n;e.fill(0);for(let l=0;l<o;l++){const u=l*s;for(let d=i[l];d<i[l+1];d++){const f=a[d]*s;for(let h=0;h<s;h++)e[u+h]+=t*(c[u+h]-c[f+h])}}for(let l=0;l<o;l++){const u=i[l+1]-i[l],d=t===0||u===0?0:r/(t*u);for(let f=l*s;f<(l+1)*s;f++)c[f]-=d*e[f]}}function WE(n,e,t){const{n:r,dim:o,emb:s,centres:i,centreCount:a,labels:c}=n;e.fill(0),t.fill(0);for(let l=0;l<r;l++){const u=c[l];for(let d=0;d<o;d++)e[u*o+d]+=s[l*o+d];t[u]++}for(let l=0;l<a;l++)if(t[l]>0)for(let u=0;u<o;u++)i[l*o+u]=e[l*o+u]/t[l]}function VE(n,e){const{n:t,dim:r,rowPtr:o,colIdx:s,emb:i,centres:a,labels:c}=n;let l=0,u=0,d=0;for(let f=0;f<t;f++){const h=di(i,f,a,c[f],r);l+=h*h}for(let f=0;f<t;f++)for(let h=o[f];h<o[f+1];h++){const g=di(i,f,i,s[h],r);u+=g*g}for(const f of i)d+=f*f;return l+e*u+e*d}function jE(n,e){return n.every((t,r)=>t===e[r])}function qE(n,e){const{numClusters:t,maxIterations:r=1e3,tolerance:o=1e-6,seed:s=42,learningRate:i=.5,lambda:a=.1}=e,c=n.nodeCount;if(c===0)return{...We(new Uint32Array(0),t),embeddings:new Float64Array(0),dimensions:0,loss:0,previousLoss:1/0,iterations:0,converged:!0};if(!Number.isInteger(t)||t<=0||t>c)throw Q(new Error(`Invalid number of clusters: ${String(t)}. Must be between 1 and ${String(c)}`),"E_BAD_OPTION");const l=no(s),u=Math.min(64,c),d={n:c,dim:u,rowPtr:n.rowPtr,colIdx:n.colIdx,emb:UE(n,l,u),centres:new Float64Array(t*u),centreCount:0,labels:new Uint32Array(c)};zE(d,t,l);const f=new Float64Array(c*u),h=new Float64Array(t*u),g=new Uint32Array(t);let w=1/0,p=1/0,m=0,y=!1;const b=new Uint32Array(c);let v=0;for(;m<r;)if(m++,og(d),v=m>1&&jE(d.labels,b)?v+1:0,b.set(d.labels),GE(d,f,a,i),WE(d,h,g),m>1&&(w=p),p=VE(d,a),Math.abs(w-p)<o||v>=ME){y=!0;break}return og(d),{...We(d.labels,t),embeddings:d.emb,dimensions:u,loss:p,previousLoss:w,iterations:m,converged:y}}const HE=100;function KE(n,e,t){const r=n.nodeCount;if(!e){for(let s=0;s<r;s++)for(let i=s+1;i<r;i++)t[s*r+i]=t[i*r+s]=n.hasArc(s,i)?1:2;return}t.fill(1/0);const o=new Uint32Array(r);for(let s=0;s<r;s++)YE(n,s,t,o)}function YE(n,e,t,r){const o=e*n.nodeCount;t[o+e]=0,r[0]=e;let s=0,i=1;for(;s<i;){const a=r[s++],c=t[o+a]+1;for(let l=n.rowPtr[a];l<n.rowPtr[a+1];l++){const u=n.colIdx[l];t[o+u]===1/0&&(t[o+u]=c,r[i++]=u)}}}function XE(n,e={}){const{linkage:t="average",numClusters:r,distanceThreshold:o,useGraphDistance:s=!0}=e;if(r!==void 0&&(r<1||!Number.isInteger(r)))throw Q(new Error("numClusters must be a positive integer"),"E_BAD_OPTION");const i=n.nodeCount;if(i===0)throw Q(new Error("Cannot cluster empty graph"),"E_EMPTY_GRAPH");const a=Lf("teraHAC",i,e.maxNodes,8*i*i,()=>new Float64Array(i*i));if(KE(n,s,a),t==="ward")for(let D=0;D<a.length;D++)a[D]*=a[D];const l={single:Math.min,complete:Math.max,average:null,ward:null}[t],u=Math.max(0,i-1),d=new Uint32Array(u),f=new Uint32Array(u),h=new Float64Array(u),g=new Uint32Array(u),w=new Uint32Array(i),p=new Uint32Array(i).fill(1),m=new Uint8Array(i).fill(1);for(let D=0;D<i;D++)w[D]=D;const y=(D,U)=>{const B=w[D],V=w[U];return B<i&&V<i?B<V:B>V},b=(D,U)=>{const[B,V]=y(D,U)?[D,U]:[U,D];let W=a[B*i+V];return w[B]<i&&w[V]<i?W=t==="ward"?Math.sqrt(W):W:l||(W/=p[B]*p[V]),W===1/0?HE:W},v=(D,U)=>{const B=w[D],V=w[U],W=Math.min(B,V),q=Math.max(B,V);return q<i?W*i+q:i*i+q*2*i+W},A=new Int32Array(i).fill(-1),E=new Float64Array(i),I=new Float64Array(i),k=(D,U)=>{const B=b(D,U),V=v(D,U);(A[D]===-1||B<E[D]||B===E[D]&&V<I[D])&&(A[D]=U,E[D]=B,I[D]=V)},N=D=>{A[D]=-1;for(let U=0;U<i;U++)m[U]&&U!==D&&k(D,U)};for(let D=0;D<i;D++)N(D);let C=i,O=0;for(;C>1&&(r===void 0||C>r);){let D=-1;for(let W=0;W<i;W++)m[W]&&(D===-1||E[W]<E[D]||E[W]===E[D]&&I[W]<I[D])&&(D=W);const U=E[D];if(o!==void 0&&U>o)break;const[B,V]=y(D,A[D])?[D,A[D]]:[A[D],D];d[O]=w[B],f[O]=w[V],h[O]=U,g[O]=p[B]+p[V];for(let W=0;W<i;W++)if(m[W]&&W!==B&&W!==V){const q=B*i+W,K=V*i+W,X=W*i+B,H=W*i+V;a[q]=l?l(a[q],a[K]):a[q]+a[K],a[X]=l?l(a[X],a[H]):a[X]+a[H]}w[B]=i+O,p[B]=g[O],m[V]=0,O++,C--,N(B);for(let W=0;W<i;W++)m[W]&&W!==B&&(A[W]===B||A[W]===V?N(W):k(W,B))}const T=Array.from(w.filter((D,U)=>m[U]===1)).sort((D,U)=>D-U);let $=T[0];const L=D=>D<i?1:g[D-i];for(let D=1;D<T.length;D++){const U=O+D-1;d[U]=$,f[U]=T[D],h[U]=1/0,g[U]=L($)+L(T[D]),$=i+U}const F=QE(i,d,f,$,r??C),{labels:M,count:R}=Je(F);return{...We(M,R),left:d,right:f,distance:h,size:g,merges:O,root:$}}function QE(n,e,t,r,o){const s=[],i=[r];let a=0;for(;a<i.length&&s.length<o;){const l=i[a++];l<n||o===1||s.length+(i.length-a)+1>=o?s.push(l):i.push(e[l-n],t[l-n])}const c=new Uint32Array(n);return s.forEach((l,u)=>{const d=[l];for(;d.length>0;){const f=d.pop()??0;f<n?c[f]=u:d.push(e[f-n],t[f-n])}}),c}function JE(n,e,t){let r=e;for(let o=e;o<t;o++)(o===e||n[o]!==n[o-1])&&(n[r++]=n[o]);return r}function sg(n){const e=n.nodeCount,t=n.directed?[n,n.reverse()]:[n],r=new Uint32Array(e+1),o=new Uint32Array(t.reduce((i,a)=>i+a.colIdx.length,0));let s=0;for(let i=0;i<e;i++){r[i]=s;const a=s;for(const l of t)for(let u=l.rowPtr[i];u<l.rowPtr[i+1];u++)l.colIdx[u]!==i&&(o[s++]=l.colIdx[u]);const c=o.subarray(a,s);t.length>1&&c.sort(),s=JE(o,a,s)}return r[e]=s,{rowPtr:r,colIdx:o.slice(0,s)}}function ig(n,e,t){const r=n.length,o=new Float64Array(r);let s=0;for(let i=0;i<r;i++){const a=t[i+1]-t[i],c=a*(a-1)/2;s+=c,o[i]=c>0?n[i]/c:0}return{coefficient:o,transitivity:s>0?3*e/s:0}}function ZE(n,e,t,r,o){let s=0,i=e[t],a=e[r];const c=e[t+1],l=e[r+1];for(;i<c&&a<l;)n[i]<n[a]?i++:(n[i]>n[a]||(o[t]++,o[r]++,o[n[i]]++,s++,i++),a++);return s}function ag(n){const e=n.nodeCount,{rowPtr:t,colIdx:r}=sg(n),o=(u,d)=>{const f=t[u+1]-t[u],h=t[d+1]-t[d];return h>f||h===f&&d>u},s=new Uint32Array(e+1),i=new Uint32Array(r.length/2);let a=0;for(let u=0;u<e;u++){s[u]=a;for(let d=t[u];d<t[u+1];d++)o(u,r[d])&&(i[a++]=r[d])}s[e]=a;const c=new Uint32Array(e);let l=0;for(let u=0;u<e;u++){const d=s[u+1];for(let f=s[u];f<d;f++)l+=ZE(i,s,u,i[f],c)}return{perNode:c,total:l,...ig(c,l,t)}}function $t(n){return new Promise(e=>{e(n())})}function cg(n,e){if(n.sigmaOverflow===!0)throw new ZA(e);return n}function lg(n,e){return{normalized:e?.normalized,sources:is(n,e?.sources,e?.k)}}function e_(n,e,t){const r=t?.sources!==void 0||t?.k!==void 0,o=t?.harmonic===!0;return(!r||!e.directed)&&(!o||n.harmonicCloseness===!0&&!r)&&t?.normalized!==!0&&t?.cutoff===void 0&&t?.weights===void 0}function t_(n,e){const t=e?.weighted===!0;return e?.sources===void 0&&e?.k===void 0?e?.harmonic===!0?{weighted:t,harmonic:!0}:{weighted:t}:{weighted:t,sources:is(n,e.sources,e.k,"closenessCentrality")}}function n_(n,e){return e?.weights===void 0&&(e?.method??"auto")==="auto"&&e?.maxNodes===void 0&&e?.paths!==!0&&e?.weighted!==!1&&n.nodeCount<=zf&&n.flags.nonNegativeWeights&&n.flags.finiteWeights}function ug(n){return n?.initialRanks!==void 0||n?.convergenceNorm==="max"}function dg(n){return{dampingFactor:n?.dampingFactor,maxIterations:n?.maxIterations,tolerance:n?.tolerance,weighted:n?.weighted===!0}}function r_(n,e,t){const r=t?.weighted===!0&&n.weights!==null?n.weightedOutDegree():n.outDegree();return ug(t)||!e.some(o=>o>0)||r.includes(0)}function o_(n,e){return e?.startVector===void 0&&!n.directed&&!n.flags.multigraph&&!s_(n)}function s_(n){const e=n.nodeCount,t=new Int8Array(e).fill(-1),r=new Uint32Array(e);for(let o=0;o<e;o++){if(t[o]!==-1||n.rowPtr[o]===n.rowPtr[o+1])continue;t[o]=0;let s=0;r[s++]=o;let i=!1;for(let a=0;a<s;a++){const c=r[a];for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];t[u]===-1?(t[u]=1-t[c],r[s++]=u):t[u]===t[c]&&(i=!0)}}if(!i)return!0}return!1}function i_(n,e){if(!n.converged)throw new Mf("eigenvectorCentrality",e?.maxIterations??100,e?.tolerance??1e-6);if(e?.normalized===!1)return n;const t=Float64Array.from(n.scores);return dh(t),{scores:t,iterations:n.iterations,converged:!0}}function a_(n,e){if(e?.normalized===!1||e?.alpha===0)return!1;const t=n.reverse(),r=e?.weighted===!0?t.weights:null,o=new Float64Array(n.nodeCount);let s,i=!1;for(let l=0;l<n.nodeCount;l++){let u=0;for(let d=t.rowPtr[l];d<t.rowPtr[l+1];d++)u+=r===null?1:r[d],o[l]+=r===null?1:Math.abs(r[d]);s??(s=u),i||(i=u!==s)}if(!i)return!1;let a=0;for(let l=0;l<n.nodeCount;l++)for(let u=t.rowPtr[l];u<t.rowPtr[l+1];u++)a=Math.max(a,o[l]*o[t.colIdx[u]]);const c=e?.alpha??.1;return c*c*a<1}function c_(n){let e=1/0,t=-1/0;for(const o of n)e=Math.min(e,o),t=Math.max(t,o);const r=t-e;if(r>0)for(let o=0;o<n.length;o++)n[o]=(n[o]-e)/r}function l_(n){const e=Float64Array.from(n.scores);return c_(e),{scores:e,iterations:n.iterations,converged:n.converged}}function fg(n,e){let t=0;for(const r of n)t=e==="l2"?t+r*r:Math.max(t,r);if(t=e==="l2"?Math.sqrt(t):t,t>0)for(let r=0;r<n.length;r++)n[r]/=t}function u_(n,e){const t=e?.normalized===!1?"max":"l2",r=Float64Array.from(n.hubs),o=Float64Array.from(n.authorities);return fg(r,t),fg(o,t),{hubs:r,authorities:o,iterations:n.iterations,converged:n.converged}}function hg(n,e,t){const{predArc:r}=t;return{dist:t.dist,predArc:r,pathTo:o=>Jr(n,r,e,o),pathEdges:o=>Zr(n,r,e,o)}}function d_(n,e){const{perNode:t,total:r,coefficient:o,transitivity:s}=e;return o!==void 0&&s!==void 0?{perNode:t,total:r,coefficient:o,transitivity:s}:{perNode:t,total:r,...ig(t,r,sg(n).rowPtr)}}function f_(n){return{accelerator:n??null,pageRank:(e,t)=>n?.pageRank!==void 0&&!ug(t)?n.pageRank(e,dg(t)):Promise.resolve(Xh(e,t)),personalizedPageRank:(e,t,r)=>n?.personalizedPageRank!==void 0&&!r_(e,t,r)?n.personalizedPageRank(e,t,dg(r)):Promise.resolve(Qh(e,t,r)),eigenvectorCentrality:(e,t)=>n?.eigenvectorCentrality!==void 0&&o_(e,t)?n.eigenvectorCentrality(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:!1}).then(r=>i_(r,t)):new Promise(r=>{r(uh(e,t))}),sssp:(e,t,r)=>{const o=xe(e,t);return n?.sssp!==void 0?n.sssp(e,o,r).then(s=>hg(e,o,s)):Promise.resolve(Bf(e,o,r))},bellmanFord:(e,t,r)=>{const o=xe(e,t);return n?.bellmanFord!==void 0&&(r?.weights===void 0||r.weights instanceof Float32Array)?n.bellmanFord(e,o,r).then(s=>({...hg(e,o,s),hasNegativeCycle:s.hasNegativeCycle})):Promise.resolve(Wf(e,o,r))},breadthFirstSearch:(e,t,r)=>{const o=xe(e,t);return n?.breadthFirstSearch!==void 0&&r?.target===void 0&&r?.arcOrder===void 0?n.breadthFirstSearch(e,o,r):Promise.resolve(Kf(e,o,r))},connectedComponents:e=>n?.connectedComponents!==void 0?n.connectedComponents(e):Promise.resolve(th(e)),weaklyConnectedComponents:e=>n?.weaklyConnectedComponents!==void 0?n.weaklyConnectedComponents(e):Promise.resolve(nh(e)),minimumSpanningTree:(e,t)=>n?.minimumSpanningTree!==void 0&&t?.weights===void 0?n.minimumSpanningTree(e):Promise.resolve(Kh(e,t)),kCoreDecomposition:e=>n?.kCoreDecomposition!==void 0?n.kCoreDecomposition(e):Promise.resolve(kh(e)),katzCentrality:(e,t)=>n?.katzCentrality!==void 0&&a_(e,t)?n.katzCentrality(e,{alpha:t?.alpha,beta:t?.beta,maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(l_):Promise.resolve(Sh(e,t)),hits:(e,t)=>n?.hits!==void 0?n.hits(e,{maxIterations:t?.maxIterations,tolerance:t?.tolerance,weighted:t?.weighted===!0}).then(r=>u_(r,t)):Promise.resolve(Ah(e,t)),louvain:(e,t)=>n?.louvain!==void 0?n.louvain(e,t):Promise.resolve(Gh(e,t)),allPairsShortestPath:(e,t)=>n?.allPairsShortestPath!==void 0&&n_(e,t)?n.allPairsShortestPath(e).then(({dist:r,n:o})=>({dist:r,n:o,hasNegativeCycle:!1})):Promise.resolve(Gf(e,t)),betweennessCentrality:(e,t)=>n?.betweennessCentrality!==void 0&&!e.flags.multigraph&&t?.endpoints!==!0?n.betweennessCentrality(e,lg(e,t)).then(r=>cg(r,"betweennessCentrality")):Promise.resolve(qf(e,t)),edgeBetweennessCentrality:(e,t)=>n?.edgeBetweennessCentrality!==void 0&&!e.flags.multigraph&&t?.alive===void 0?n.edgeBetweennessCentrality(e,lg(e,t)).then(r=>cg(r,"edgeBetweennessCentrality")):Promise.resolve(dc(e,t)),closenessCentrality:(e,t)=>n?.closenessCentrality!==void 0&&e_(n,e,t)?n.closenessCentrality(e,t_(e,t)):Promise.resolve(Jf(e,t)),labelPropagation:(e,t)=>n?.labelPropagation!==void 0&&t?.randomSeed===void 0?n.labelPropagation(e,t):Promise.resolve(ph(e,t)),labelPropagationSynchronous:(e,t)=>n?.labelPropagation!==void 0?n.labelPropagation(e,{maxIterations:t?.maxIterations,weighted:t?.weighted}):Promise.resolve(mh(e,t)),triangleCount:e=>n?.triangleCount!==void 0?n.triangleCount(e).then(t=>d_(e,t)):Promise.resolve(ag(e)),depthFirstSearch:(e,t,r)=>$t(()=>lh(e,t,r)),degrees:e=>$t(()=>oh(e)),stronglyConnectedComponents:(e,t)=>$t(()=>Nc(e,t)),leiden:(e,t)=>$t(()=>Ch(e,t)),girvanNewman:(e,t)=>$t(()=>yh(e,t)),maxFlow:(e,t,r,o)=>$t(()=>_c(e,t,r,o)),minSTCut:(e,t,r,o)=>$t(()=>hh(e,t,r,o)),stoerWagner:(e,t)=>$t(()=>qh(e,t)),kargerMinCut:(e,t)=>$t(()=>Hh(e,t)),commonNeighborsPrediction:(e,t)=>$t(()=>Mh(e,t)),adamicAdarPrediction:(e,t)=>$t(()=>Fh(e,t)),primMST:(e,t)=>$t(()=>Yh(e,t)),maximumBipartiteMatching:(e,t)=>$t(()=>jh(e,t))}}const h_={graphtyAStar:["directed","goal","gpu","heuristic","root","weight"],graphtyAdamicAdarForPairs:["directed","gpu","pairs"],graphtyAdamicAdarPrediction:["directed","gpu","includeExisting","topK"],graphtyAdamicAdarScore:["directed","gpu","source","target"],graphtyAllPairsShortestPath:["directed","gpu","maxNodes","method","paths","weight"],graphtyBellmanFord:["cutoff","directed","field","gpu","root","weight"],graphtyBetweennessCentrality:["directed","endpoints","field","gpu","k","normalized","sources"],graphtyBidirectionalDijkstra:["directed","goal","gpu","root","weight"],graphtyBreadthFirstSearch:["directed","field","goal","gpu","maxDepth","root"],graphtyClosenessCentrality:["cutoff","directed","field","gpu","harmonic","k","normalized","sources","weight"],graphtyCommonNeighborsForPairs:["directed","gpu","pairs"],graphtyCommonNeighborsPrediction:["directed","gpu","includeExisting","topK"],graphtyCommonNeighborsScore:["directed","gpu","source","target"],graphtyCompareAdamicAdarWithCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyCondensation:["directed","field","gpu"],graphtyConnectedComponents:["directed","field","gpu"],graphtyDegreeCentrality:["directed","field","gpu","mode","normalized"],graphtyDegrees:["directed","gpu"],graphtyDeltaPageRank:["dampingFactor","deltaThreshold","directed","field","gpu","maxIterations","personalization","priority","tolerance","weight"],graphtyDepthFirstSearch:["directed","field","goal","gpu","order","root"],graphtyDijkstra:["cutoff","directed","field","gpu","root","weight"],graphtyDirectionOptimizedBfs:["alpha","beta","directed","field","gpu","root"],graphtyEdgeBetweennessCentrality:["directed","field","gpu","k","normalized","sources"],graphtyEigenvectorCentrality:["directed","field","gpu","maxIterations","mode","normalized","startVector","tolerance"],graphtyEvaluateAdamicAdar:["directed","edges","gpu","nonEdges"],graphtyEvaluateCommonNeighbors:["directed","edges","gpu","nonEdges"],graphtyFindAllIsomorphisms:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyGirvanNewman:["directed","field","gpu","maxCommunities","maxIterations","minCommunitySize","weight"],graphtyGreedyBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyGrsbm:["directed","field","gpu","maxDepth","maxIterations","minClusterSize","seed","tolerance","weight"],graphtyHasCycle:["directed","gpu"],graphtyHierarchicalClustering:["directed","gpu","linkage","maxNodes"],graphtyHits:["directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyIsBipartite:["arcs","directed","field","gpu"],graphtyIsGraphIsomorphic:["directed","edgeMatch","gpu","nodeMatch","other"],graphtyKCoreDecomposition:["directed","field","gpu"],graphtyKargerMinCut:["directed","field","gpu","iterations","randomSeed","weight"],graphtyKatzCentrality:["alpha","beta","directed","field","gpu","maxIterations","normalized","tolerance","weight"],graphtyKruskalMST:["directed","gpu","weight"],graphtyLabelPropagation:["directed","field","gpu","maxIterations","randomSeed","weight"],graphtyLabelPropagationSemiSupervised:["directed","field","gpu","maxIterations","randomSeed","seeds","weight"],graphtyLabelPropagationSynchronous:["directed","field","gpu","maxIterations","weight"],graphtyLeiden:["directed","field","gpu","maxIterations","randomSeed","resolution","threshold","weight"],graphtyLouvain:["directed","field","gpu","maxIterations","resolution","tolerance","weight"],graphtyMarkovClustering:["directed","expansion","field","gpu","inflation","maxIterations","pruningThreshold","selfLoops","tolerance","weight"],graphtyMaxFlow:["algorithm","directed","field","gpu","sink","source","weight"],graphtyMaximumBipartiteMatching:["arcs","directed","gpu","left","right"],graphtyMinSTCut:["algorithm","directed","field","gpu","sink","source","weight"],graphtyModularity:["clusters","directed","gpu","resolution","weight"],graphtyNodeClosenessCentrality:["cutoff","directed","gpu","harmonic","normalized","root","weight"],graphtyPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","tolerance","weight"],graphtyPersonalizedPageRank:["convergenceNorm","dampingFactor","directed","field","gpu","initialRanks","maxIterations","personalization","tolerance","weight"],graphtyPrimMST:["directed","forest","gpu","root","weight"],graphtySpectralClustering:["directed","field","gpu","k","laplacianType","maxIterations","seed","tolerance","weight"],graphtyStoerWagner:["directed","field","gpu","weight"],graphtyStronglyConnectedComponents:["directed","field","gpu"],graphtySyncClustering:["directed","field","gpu","lambda","learningRate","maxIterations","numClusters","seed","tolerance"],graphtyTeraHAC:["directed","distanceThreshold","field","gpu","linkage","maxNodes","numClusters","useGraphDistance"],graphtyTopAdamicAdarCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopCandidatesForNode:["candidates","directed","gpu","includeExisting","root","topK"],graphtyTopologicalSort:["directed","gpu"],graphtyTriangleCount:["directed","field","gpu"],graphtyWeaklyConnectedComponents:["directed","field","gpu"]},g_={ak:["k"],"balanced-tree":["branching","height","seed","weights"],"barabasi-albert":["m","n","seed","triadProbability","weights"],barbell:["cliqueSize","pathLength","seed","weights"],"bianconi-barabasi":["fitness","m","n","seed","weights"],"bipartite-configuration-model":["leftDegrees","multiEdges","rightDegrees","seed","weights"],caveman:["cliques","seed","size","weights"],"chung-lu":["expectedDegrees","seed","weights"],"circular-ladder":["n","seed","weights"],complete:["n","seed","weights"],"complete-bipartite":["a","b","seed","weights"],"complete-multipartite":["seed","sizes","weights"],"configuration-model":["degrees","multiEdges","seed","selfLoops","weights"],"connected-caveman":["cliques","seed","size","weights"],cycle:["n","seed","weights"],"degree-corrected-sbm":["expectedDegrees","mixing","seed","sizes","weights"],"directed-configuration-model":["inDegrees","multiEdges","outDegrees","seed","selfLoops","weights"],"duplication-divergence":["n","retention","seed","weights"],empty:["n","seed","weights"],"erdos-renyi":["directed","n","p","seed","weights"],"erdos-renyi-gnm":["m","n","seed","weights"],"forest-fire":["backward","forward","maxBurn","n","seed","weights"],genrmf:["a","b","c1","c2","seed"],grid:["cols","diagonals","directed","obstacles","periodic","positions","rows","seed","weights"],"grid-3d":["cols","diagonals","directed","layers","obstacles","periodic","positions","rows","seed","weights"],"grid-flow-network":["cols","maxCapacity","minCapacity","rows","seed"],"hexagonal-lattice":["cols","positions","rows","seed","weights"],hyperbolic:["averageDegree","exponent","n","seed","temperature","weights"],hypercube:["dimension","seed","weights"],knn:["clusters","dimension","directed","k","n","seed","spread","weights"],kronecker:["directed","edges","initiator","multiEdges","permute","power","seed","selfLoops","weights"],ladder:["n","seed","weights"],"layered-flow-network":["layers","maxCapacity","minCapacity","p","seed"],lfr:["communityExponent","degreeExponent","maxCommunity","maxDegree","minCommunity","minDegree","mixing","n","seed","weights"],lollipop:["cliqueSize","pathLength","seed","weights"],"mobius-ladder":["n","seed","weights"],named:["name","seed","weights"],"newman-watts":["k","n","p","seed","weights"],path:["n","seed","weights"],petersen:["seed","weights"],"planted-partition":["groupSize","groups","pIn","pOut","seed","weights"],price:["attractiveness","citations","n","seed","weights"],"random-apollonian":["n","seed","weights"],"random-bipartite":["n1","n2","p","perfectMatching","seed","weights"],"random-dag":["layers","p","seed","weights"],"random-geometric":["dimension","n","periodic","radius","seed","weights"],"random-order-dag":["n","p","seed","weights"],"random-recursive-tree":["n","seed","weights"],"random-regular":["d","n","seed","weights"],"random-tree":["n","seed","weights"],"ring-of-cliques":["cliques","seed","size","weights"],rmat:["a","b","c","d","directed","edgeFactor","multiEdges","permute","scale","seed","selfLoops","weights"],star:["n","seed","weights"],"stochastic-block-model":["probabilities","seed","sizes","weights"],"triangular-lattice":["cols","positions","rows","seed","weights"],"watts-strogatz":["beta","k","n","seed","weights"],waxman:["alpha","beta","n","seed","weights"],wheel:["n","seed","weights"],"wilson-maze":["cols","rows","seed","weights"]},gg=5e3;function as(n,e){const t=setTimeout(()=>{console.warn(`graphty: ${e} has waited ${String(gg/1e3)} s for part of @graphty/cytoscape-extensions to load. If a module awaits ${e} at its top level, a Vite 6 or 7 production build never loads it: call it inside an async function, or with .then(), instead. On a slow network the call carries on.`)},gg),r=()=>{clearTimeout(t)};return n.then(r,r),n}const wg=new WeakMap,so=new Map,Tc=new Map;function fi(n){return n.cy()}function pg(n){let e=wg.get(n);if(e===void 0){const t={version:0,entries:[],dropListeners:new Set};n.on("add remove data move",()=>{t.version++,mg(t,t.entries),t.entries=[]}),wg.set(n,t),e=t}return e}function mg(n,e){const t=[];for(const{value:r}of e)so.has(r.snapshot)?Tc.set(r.snapshot,n):t.push(r.snapshot);yg(n,t)}function yg(n,e){if(e.length>0)for(const t of n.dropListeners)t(e)}function bg(n){so.set(n,(so.get(n)??0)+1);let e=!0;return()=>{if(!e)return;e=!1;const t=(so.get(n)??1)-1;if(t>0){so.set(n,t);return}so.delete(n);const r=Tc.get(n);r!==void 0&&(Tc.delete(n),yg(r,[n]))}}function w_(n,e){const t=pg(n);return t.dropListeners.add(e),()=>{t.dropListeners.delete(e)}}function hi(n,e={}){const t=e.directed??!1,r=n;if(typeof e.weight=="function")return vg(r,t,e.weight);const o=`${String(t)}|${e.weight??""}`,s=pg(fi(n)),i=s.entries.find(c=>c.key===o&&c.version===s.version&&p_(c.eles,r));if(i!==void 0)return i.value;const a=vg(r,t,e.weight);return mg(s,s.entries.filter(c=>c.key===o)),s.entries=[...s.entries.filter(c=>c.key!==o),{key:o,eles:r,version:s.version,value:a}],a}function p_(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function vg(n,e,t){const r=n.nodes(),o=[],s=new Map;r.forEach((d,f)=>{o.push(d.id()),s.set(d.id(),f)});const i=n.edges().filter(d=>s.has(d.source().id())&&s.has(d.target().id())),a=new Uint32Array(i.length),c=new Uint32Array(i.length),l=t===void 0?void 0:new Float64Array(i.length);return i.forEach((d,f)=>{if(a[f]=s.get(d.source().id())??0,c[f]=s.get(d.target().id())??0,l!==void 0&&t!==void 0){const h=typeof t=="function"?t(d):d.data(t);l[f]=typeof h=="number"&&Number.isFinite(h)?h:1}}),{snapshot:sc({directed:e,ids:o,src:a,dst:c,weights:l}),nodes:r,edges:i}}function io(n,e,t){fi(n).batch(()=>{n.forEach((r,o)=>{r.data(t,e[o])})})}function Gt(n,e){return(typeof e=="string"?n.nodes.filter(e):n.nodes.intersection(e)).map(r=>n.snapshot.ids.requireIndex(r.id()))}function ao(n,e,t){if(e===void 0)return;const[r]=Gt(n,e);if(r===void 0)throw new Error(`${t} matches no node of the collection`);return r}class Oc extends Error{constructor(e,t,r=null){super(t),this.name="GpuUnavailableError",this.code=e,this.fix=r}}function cs(){return Object.assign(new Error("graphty: the Cytoscape core was destroyed"),{code:"E_CORE_DESTROYED"})}const m_=["auto","off","require"];function $c(n,e){if(e!==void 0&&!m_.includes(e)){const r=e===null||typeof e=="number"||typeof e=="boolean"?String(e):`a value of type ${typeof e}`,o=typeof e=="string"?JSON.stringify(e):r;throw new TypeError(`${n}: gpu must be "auto", "off" or "require"; got ${o}`)}}const Ag=5e3;let Eg={},y_,Pr=null,Xn=null,Rc=!1;const _g=new WeakMap;function b_(n={}){Eg={...n},Pr=null,Xn=null,Rc=!1}function Ig(){const n=globalThis.navigator;return n?.gpu!==void 0&&n.gpu!==null?null:globalThis.process?.versions?.node===void 0?"this runtime has no WebGPU (navigator.gpu is undefined)":null}function v_(){if(Pr===null){const n=Ig();if(n!==null)Xn={reason:n??"WebGPU was disabled",fix:null},Pr=Promise.resolve(Xn);else{const e=as(Promise.resolve().then(()=>jO),"an ...Async method or a simulation layout").then(t=>t.gpuProvider(Eg),t=>({reason:`@graphty/webgpu-graph-algorithms did not load: ${Sg(t)}`,fix:"check that @graphty/webgpu-graph-algorithms is installed and that your bundler serves its chunk"}));Pr=e,e.then(t=>{Pr===e&&(Xn=t)})}}return Pr}function kg(n){return"acquire"in n}function Sg(n){return n instanceof Error?n.message:String(n)}function Pg(n){n?.then(e=>e.gpu?.accelerator.dispose(),()=>{})}function A_(n){let e=_g.get(n);if(e===void 0){const t={decision:null,by:null,destroyed:!1};n.one("destroy",()=>{t.destroyed=!0,Pg(t.decision),t.decision=null}),_g.set(n,t),e=t}return e}async function E_(n,e,t){let r;try{r=await t.acquire()}catch(i){const a=i instanceof Oc?i.fix:null;return{gpu:null,reason:`no usable WebGPU device: ${Sg(i)}`,fix:a}}if(e.destroyed)return r.accelerator.dispose(),{gpu:null,reason:"the core was destroyed"};const o=w_(n,i=>{for(const a of i)r.accelerator.release(a)}),s=e.decision;return r.lost.then(()=>{o(),e.decision===s&&(e.decision=null)}),{gpu:r,reason:null}}function xg(n="auto"){if(n==="off")return{gpu:null,reason:'gpu: "off" was requested',fix:null};if(Pr===null&&y_===void 0){const e=Ig();if(e!==null)return{gpu:null,reason:e,fix:null}}return Xn===null||kg(Xn)?null:{gpu:null,...Xn}}async function Cg(n,e="auto"){let t=xg(e);if(t===null){const r=A_(n),o=v_(),s=Xn??await o;if(!kg(s))t={gpu:null,...s};else{if(r.destroyed)throw cs();(r.decision===null||r.by!==s)&&(Pg(r.decision),r.decision=Promise.resolve().then(()=>E_(n,r,s)),r.by=s),t=await r.decision}}if(e==="require"&&t.gpu===null)throw new Error(`graphty: gpu: "require" but ${t.reason??"no device"}`);return t}function Dc(n,e){Rc||n.gpu!==null||n.fix===void 0||n.fix===null||e<Ag||(Rc=!0,console.warn(`graphty: a ${e.toLocaleString("en-US")}-node graph ran on the CPU because ${n.reason??"no GPU"}. To use the GPU: ${n.fix}. Pass gpu: "off" to run on the CPU without this warning.`))}function __(n){let e=!1;return{accelerator:new Proxy(n,{get(r,o,s){const i=Reflect.get(r,o,s);return typeof i!="function"||o==="release"||o==="dispose"?i:(...a)=>(e=!0,i.apply(r,a))}}),used:()=>e}}function Lc(n,e,t){return n.gpu===null?{ran:"cpu",reason:n.reason,device:null}:e?{ran:"gpu",reason:null,device:n.gpu.device}:{ran:"cpu",reason:t,device:n.gpu.device}}const I_={breadthFirstSearch:Kf,sssp:Bf,bellmanFord:Wf,allPairsShortestPath:Gf,pageRank:Xh,personalizedPageRank:Qh,eigenvectorCentrality:uh,katzCentrality:Sh,hits:Ah,closenessCentrality:Jf,betweennessCentrality:qf,edgeBetweennessCentrality:dc,connectedComponents:th,weaklyConnectedComponents:nh,triangleCount:ag,labelPropagation:ph,labelPropagationSynchronous:mh};function ct(n,e){return n instanceof Promise?n.then(e):e(n)}const k_=new Set(["gpu","directed","weight","field","root","goal","target","source","sink","heuristic","personalization","seeds","left","right","clusters","pairs","edges","nonEdges","nodeMatch","edgeMatch","priority","candidates","sources","alive","startVector","initialRanks"]),S_=new Set(["breadthFirstSearch","directionOptimizedBfs","depthFirstSearch","hasCycle","topologicalSort","degreeCentrality","degrees","eigenvectorCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","stronglyConnectedComponents","condensation","kCoreDecomposition","triangleCount","isBipartite","isGraphIsomorphic","findAllIsomorphisms","hierarchicalClustering","teraHAC","syncClustering","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),P_=new Set(["hasCycle","topologicalSort","bidirectionalDijkstra","aStar","allPairsShortestPath","degrees","nodeClosenessCentrality","isGraphIsomorphic","findAllIsomorphisms","modularity","hierarchicalClustering","kruskalMST","primMST","maximumBipartiteMatching","greedyBipartiteMatching","commonNeighborsScore","adamicAdarScore","commonNeighborsPrediction","adamicAdarPrediction","commonNeighborsForPairs","adamicAdarForPairs","topCandidatesForNode","topAdamicAdarCandidatesForNode","evaluateCommonNeighbors","evaluateAdamicAdar","compareAdamicAdarWithCommonNeighbors"]),gi={maxIterations:100,tolerance:1e-6},Mc={...gi,dampingFactor:.85},x_={pageRank:Mc,personalizedPageRank:Mc,deltaPageRank:Mc,eigenvectorCentrality:gi,hits:gi,katzCentrality:{...gi,alpha:.1,beta:1},labelPropagation:{maxIterations:100},labelPropagationSynchronous:{maxIterations:100},labelPropagationSemiSupervised:{maxIterations:100},allPairsShortestPath:{paths:!0},maxFlow:{algorithm:"edmonds-karp"},minSTCut:{algorithm:"ford-fulkerson"}},Ng=new Set(["topologicalSort","stronglyConnectedComponents","condensation","deltaPageRank"]);function ls(n,e){return n.cy.collection(e)}function Uc(n){if(n.s.weights?.some(e=>e<0)===!0)throw Object.assign(new Error(`${n.name}: a weight is negative; use graphtyBellmanFord`),{code:"E_BAD_WEIGHT"})}function Be(n,e,t){const r=ao(n.cs,e,`${n.name}: ${t}`);if(r===void 0)throw new Error(`${n.name}: the ${t} option is required`);return r}function bn(n,e,t=!1){const r=t?n.cs.edges:n.cs.nodes,s=(typeof e=="string"?r.filter(e):e)[0];if(s===void 0)return;if(!t){const a=n.s.ids.indexOf(s.id());return a===x?void 0:a}const i=n.cs.edges.toArray().indexOf(s);return i<0?void 0:i}function Et(n,e,t=!1){return r=>{const o=bn(n,r,t);return o===void 0?void 0:e[o]}}function us(n,e){return ls(n,Array.from(e,t=>n.cs.nodes[t]))}function Fc(n,e){return ls(n,Array.from(e,t=>n.cs.edges[t]))}function wi(n,e,t){const r=[];for(let o=0;o<e.length;o++)o>0&&r.push(n.cs.edges[t[o-1]]),r.push(n.cs.nodes[e[o]]);return ls(n,r)}function Qn(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);return{sources:e.map(r=>Be(n,r[0],t)),targets:e.map(r=>Be(n,r[1],t))}}function pi(n,e){if(e===void 0)return;const t=At(n.s.nodeCount);for(const r of Gt(n.cs,e))pn(t,r,!0);return t}function Zt(n,e,t,r=!1){return n.field!==void 0&&io(r?n.cs.edges:n.cs.nodes,e,n.field),{score:Et(n,e,r),...t}}function lt(n,e,t){const r=[];for(let s=0;s<e.length;s++){const i=e[s];if(i!==x){const a=r[i]??[];a.push(s),r[i]=a}}n.field!==void 0&&io(n.cs.nodes,e,n.field);const o=Array.from(r,s=>us(n,s??[]));return Object.assign(o,t,{cluster:s=>{const i=bn(n,s);return i===void 0||e[i]===x?void 0:e[i]}})}function Bc(n,e,t){const r=[];for(let s=0;s<e.visitedCount;s++){const i=e.order[s],a=e.parent[i];if(a!==x){const c=n.cs.nodes[a],l=n.cs.nodes[i],d=(n.s.directed?c.edgesTo(l):c.edgesWith(l)).intersection(n.cs.edges)[0];d!==void 0&&r.push(d)}r.push(n.cs.nodes[i])}const o=t!==void 0&&e.depth[t]!==x;return n.field!==void 0&&io(n.cs.nodes,Array.from(e.depth,s=>s===x?Number.NaN:s),n.field),{path:ls(n,r),found:ls(n,o?[n.cs.nodes[t]]:[]),depth:s=>{const i=bn(n,s);return i===void 0||e.depth[i]===x?void 0:e.depth[i]},parent:s=>{const i=bn(n,s);return i===void 0||e.parent[i]===x?void 0:n.cs.nodes[e.parent[i]]}}}function Tg(n,e){return n.field!==void 0&&io(n.cs.nodes,e.dist,n.field),{distanceTo:t=>{const r=bn(n,t);return r===void 0?1/0:e.dist[r]},pathTo:t=>{const r=bn(n,t);return r===void 0?n.cy.collection():wi(n,e.pathTo(r),e.pathEdges(r))}}}function zc(n,e,t,r){const o=[],s=[];for(let i=0;i<n.s.nodeCount;i++)(_e(e,i)?o:s).push(i);return n.field!==void 0&&io(n.cs.nodes,Array.from({length:n.s.nodeCount},(i,a)=>_e(e,a)?0:1),n.field),{value:r,cut:Fc(n,t),partitionFirst:us(n,o),partitionSecond:us(n,s)}}function Gc(n,e){return zc(n,e.side,e.cutEdges,e.cutValue)}function mi(n,e){return Array.from(e.scores,(t,r)=>({source:n.cs.nodes[e.sources[r]],target:n.cs.nodes[e.targets[r]],score:t}))}function Og(n,e,t){return r=>{const o=bn(n,r);return o===void 0?void 0:e.nodes[t[o]]}}function $g(n,e,t){const{nodeMatch:r,edgeMatch:o}=t;return{...n.rest,nodeMatch:r&&((s,i)=>r(n.cs.nodes[s],e.nodes[i])),edgeMatch:o&&((s,i)=>o(n.cs.edges[s],e.edges[i]))}}function Rg(n,e){const t=e.other;if(t===void 0)throw new Error(`${n.name}: the other option (the collection to compare with) is required`);let r=t;if(typeof t=="string"?r=n.cy.$(t):Array.isArray(t)&&(r=n.cy.collection(t)),typeof r?.nodes!="function")throw new TypeError(`${n.name}: the other option must be a Cytoscape collection, a selector or an array of elements`);return hi(r,{directed:n.s.directed})}function yi(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);if(typeof e=="function")return Float64Array.from(n.cs.nodes.toArray(),o=>e(o));const r=new Float64Array(n.s.nodeCount);for(const o of Gt(n.cs,e))r[o]=1;return r}function Dg(n,e){const t=yi(n,e,"personalization");if(!t.some(r=>r>0))throw new Error(`${n.name}: personalization ${typeof e=="function"?"gives no node a positive weight":"matches no node"}`);return t}function Lg(n,e,t){if(e===void 0)throw new Error(`${n.name}: the ${t} option is required`);const r=new Uint32Array(n.s.nodeCount).fill(x);if(typeof e=="string"){const o=new Map;n.cs.nodes.forEach((s,i)=>{const a=s.data(e);a!==void 0&&(r[i]=o.get(a)??o.set(a,o.size).size-1)})}else e.forEach((o,s)=>{for(const i of Gt(n.cs,o))r[i]=s});if(r.every(o=>o===x))throw new Error(typeof e=="string"?`${n.name}: ${t} names the data field "${e}", which no node has`:`${n.name}: ${t} matches no node`);return r}function C_(n,e){const t=(r,o)=>{const s=bn(n,r),i=bn(n,o);return s===void 0||i===void 0?void 0:[s,i]};return{hasNegativeWeightCycle:e.hasNegativeCycle,distance:(r,o)=>{const s=t(r,o);return s===void 0?1/0:e.dist[s[0]*e.n+s[1]]},path:(r,o)=>{const{pathTo:s,pathEdges:i}=e;if(s===void 0||i===void 0)throw new Error("allPairsShortestPath: pass paths: true to walk shortest paths");const a=t(r,o);return a===void 0?n.cy.collection():wi(n,s(a[0],a[1]),i(a[0],a[1]))}}}function Mg(n,e){return Zt(n,e.scores,{rank:Et(n,e.scores),iterations:e.iterations,converged:e.converged})}function Ug(n,e){return lt(n,e.labels,{iterations:e.iterations,converged:e.converged})}function Fg(n){return n.topK!==void 0&&n.topK<=0?1/0:n.topK}function Bg(n,e){const t=new Uint32Array(n.s.nodeCount).fill(x);return e.matching.forEach((r,o)=>{r!==x&&(t[o]=r,t[r]=o)}),{size:e.size,mate:r=>{const o=bn(n,r);return o===void 0||t[o]===x?void 0:n.cs.nodes[t[o]]}}}function N_(n){let e=0;for(let t=1;t<n.length;t++)n[t]>n[e]&&(e=t);return e}const Wc={breadthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);return ct(n.call("breadthFirstSearch",n.s,Be(n,e.root,"root"),{...n.rest,target:t}),r=>Bc(n,r,t))},directionOptimizedBfs:(n,e)=>Bc(n,l3(n.s,Be(n,e.root,"root"),n.rest),void 0),depthFirstSearch:(n,e)=>{const t=ao(n.cs,e.goal,`${n.name}: goal`);if(t!==void 0&&e.order==="post")throw new Error(`${n.name}: goal stops only a pre-order walk; leave it out with order "post"`);return Bc(n,lh(n.s,Be(n,e.root,"root"),{...n.rest,target:t}),t)},hasCycle:(n,e={})=>b3(n.s),topologicalSort:(n,e={})=>{const t=E3(n.s);return t===null?null:us(n,t)},dijkstra:(n,e)=>(Uc(n),ct(n.call("sssp",n.s,Be(n,e.root,"root"),n.rest),t=>Tg(n,t))),bellmanFord:(n,e)=>ct(n.call("bellmanFord",n.s,Be(n,e.root,"root"),n.rest),t=>({...Tg(n,t),hasNegativeWeightCycle:t.hasNegativeCycle})),bidirectionalDijkstra:(n,e)=>{Uc(n);const t=_E(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),n.rest);return{found:t.path.length>0,distance:t.distance,path:wi(n,t.path,t.edges)}},aStar:(n,e)=>{const t=e.heuristic;Uc(n);const r=kE(n.s,Be(n,e.root,"root"),Be(n,e.goal,"goal"),t===void 0?()=>0:o=>t(n.cs.nodes[o]),n.rest);return{found:r.path.length>0,distance:r.distance,path:wi(n,r.path,r.edges)}},allPairsShortestPath:(n,e={})=>ct(n.call("allPairsShortestPath",n.s,n.rest),t=>C_(n,t)),degreeCentrality:(n,e={})=>{const t=f3(n.s,n.rest);return Zt(n,t,{degree:Et(n,t)})},degrees:(n,e={})=>{const t=oh(n.s);if(!n.s.directed){const r=Float64Array.from(t.inDegree,(o,s)=>o+t.outDegree[s]);return{indegree:Et(n,r),outdegree:Et(n,r)}}return{indegree:Et(n,t.inDegree),outdegree:Et(n,t.outDegree)}},pageRank:(n,e={})=>{const t=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("pageRank",n.s,{...n.rest,initialRanks:t,weighted:n.weighted}),r=>Mg(n,r))},personalizedPageRank:(n,e)=>{const t=Dg(n,e.personalization),r=e.initialRanks&&yi(n,e.initialRanks,"initialRanks");return ct(n.call("personalizedPageRank",n.s,t,{...n.rest,initialRanks:r,weighted:n.weighted}),o=>Mg(n,o))},deltaPageRank:(n,e={})=>{const t=e.personalization===void 0?void 0:Dg(n,e.personalization),r=e.priority===!0&&e.maxIterations===void 0?{maxIterations:1/0}:{},o={...n.rest,...r,personalization:t,weighted:n.weighted},s=e.priority===!0?new p3(n.s).computeWithPriority(o):new w3(n.s).compute(o);if(s.some(i=>!Number.isFinite(i)))throw new RangeError(`${n.name}: the ranks overflowed (maxIterations ${String(n.rest.maxIterations)} is too high for this graph); lower maxIterations, or pass priority: true`);return Zt(n,s,{rank:Et(n,s)})},eigenvectorCentrality:(n,e={})=>{const t=e.startVector&&yi(n,e.startVector,"startVector");return ct(n.call("eigenvectorCentrality",n.s,{...n.rest,startVector:t}),r=>Zt(n,r.scores,{iterations:r.iterations,converged:r.converged}))},katzCentrality:(n,e={})=>ct(n.call("katzCentrality",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.scores,{iterations:t.iterations,converged:t.converged})),hits:(n,e={})=>ct(n.call("hits",n.s,{...n.rest,weighted:n.weighted}),t=>Zt(n,t.authorities,{hub:Et(n,t.hubs),authority:Et(n,t.authorities),iterations:t.iterations,converged:t.converged})),closenessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("closenessCentrality",n.s,{...n.rest,sources:t,weighted:n.weighted}),r=>Zt(n,r.scores,{closeness:Et(n,r.scores)}))},nodeClosenessCentrality:(n,e)=>u3(n.s,Be(n,e.root,"root"),{...n.rest,weighted:n.weighted}),betweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("betweennessCentrality",n.s,{...n.rest,sources:t}),r=>{const o=n.s.nodeCount,s=e.endpoints===!0?o*(o-1):(o-1)*(o-2),i=n.s.directed?1:2,a=e.normalized===!0&&s>0?s:i,c=Float64Array.from(r.scores,u=>u*a),l=c.reduce((u,d)=>Math.max(u,d),0);return Zt(n,r.scores,{betweenness:Et(n,c),betweennessNormalized:Et(n,c.map(u=>l===0?0:u/l))})})},edgeBetweennessCentrality:(n,e={})=>{const t=e.sources===void 0?void 0:Gt(n.cs,e.sources);return ct(n.call("edgeBetweennessCentrality",n.s,{...n.rest,sources:t}),r=>Zt(n,r.scores,{},!0))},connectedComponents:(n,e={})=>ct(n.call("connectedComponents",n.s),t=>lt(n,t.labels,{})),weaklyConnectedComponents:(n,e={})=>ct(n.call("weaklyConnectedComponents",n.s),t=>lt(n,t.labels,{})),stronglyConnectedComponents:(n,e={})=>lt(n,Nc(n.s).labels,{}),condensation:(n,e={})=>{const t=PE(n.s);return lt(n,t.components.labels,{condensed:t.condensed})},kCoreDecomposition:(n,e={})=>{const t=kh(n.s),r=o=>us(n,Array.from(t.coreness.keys()).filter(s=>t.coreness[s]>=o));return Zt(n,t.coreness,{maxCore:t.maxCore,core:r})},triangleCount:(n,e={})=>ct(n.call("triangleCount",n.s),t=>Zt(n,t.perNode,{coefficient:Et(n,t.coefficient),total:t.total,transitivity:t.transitivity})),isBipartite:(n,e={})=>{const t=Yf(n.s,n.rest);if(t.sides===null){const s=n.cy.collection();return{bipartite:!1,partitionFirst:s,partitionSecond:s}}const{partitionFirst:r,partitionSecond:o}=zc(n,t.sides,[],0);return{bipartite:!0,partitionFirst:r,partitionSecond:o}},isGraphIsomorphic:(n,e)=>{const t=Rg(n,e),r=H3(n.s,t.snapshot,$g(n,t,e)),o=r.mapping;return{isomorphic:r.isomorphic,mapping:o===null?()=>{}:Og(n,t,o)}},findAllIsomorphisms:(n,e)=>{const t=Rg(n,e);return K3(n.s,t.snapshot,$g(n,t,e)).map(r=>Og(n,t,r))},modularity:(n,e)=>xc(n.s,Lg(n,e.clusters,"clusters"),n.rest),louvain:(n,e={})=>{const t=Gh(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},leiden:(n,e={})=>{const t=Ch(n.s,n.rest);return lt(n,t.labels,{modularity:t.modularity,iterations:t.iterations})},labelPropagation:(n,e={})=>ct(n.call("labelPropagation",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSynchronous:(n,e={})=>ct(n.call("labelPropagationSynchronous",n.s,{...n.rest,weighted:n.weighted}),t=>Ug(n,t)),labelPropagationSemiSupervised:(n,e)=>{const t=$3(n.s,Lg(n,e.seeds,"seeds"),{...n.rest,weighted:n.weighted});return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},girvanNewman:(n,e={})=>{const t=yh(n.s,n.rest),r={...n,field:void 0},o=i=>lt(r,t.levels[i]??[],{}),s=N_(t.modularity);return lt(n,t.levels[s]??[],{modularity:t.modularity[s]??Number.NaN,levels:t.levels.length,level:o,modularities:Array.from(t.modularity)})},markovClustering:(n,e={})=>{const t=bE(n.s,n.rest);return lt(n,t.labels,{iterations:t.iterations,converged:t.converged})},spectralClustering:(n,e)=>{if(e.k===void 0)throw new Error(`${n.name}: the k option is required`);const t=LE(n.s,n.rest);return lt(n,t.labels,{converged:t.converged,eigenvalues:t.eigenvalues})},hierarchicalClustering:(n,e={})=>{const t=V3(n.s,n.rest),r={...n,field:void 0},o=i=>{const a=new Uint32Array(n.s.nodeCount).fill(x);return t.cut(i).forEach((c,l)=>{for(const u of c)a[u]=l}),lt(r,a,{})},s=i=>lt(r,t.cutAt(i).labels,{});return{merges:t.left.length,cut:o,cutAt:s}},teraHAC:(n,e={})=>{const t=XE(n.s,n.rest);return lt(n,t.labels,{merges:t.merges})},grsbm:(n,e={})=>lt(n,B3(n.s,{...n.rest,weighted:n.weighted}).labels,{}),syncClustering:(n,e)=>{if(e.numClusters===void 0)throw new Error(`${n.name}: the numClusters option is required`);const t=qE(n.s,n.rest);return lt(n,t.labels,{loss:t.loss,iterations:t.iterations,converged:t.converged})},kruskalMST:(n,e={})=>{const t=Kh(n.s);return Object.assign(n.cs.nodes.union(Fc(n,t.edges)),{totalWeight:t.totalWeight})},primMST:(n,e={})=>{const t=ao(n.cs,e.root,`${n.name}: root`),r=Yh(n.s,{...n.rest,start:t});return Object.assign(n.cs.nodes.union(Fc(n,r.edges)),{totalWeight:r.totalWeight})},maxFlow:(n,e)=>{const t=_c(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest);return{...zc(n,t.sourceSide,t.cutEdges,t.maxFlow),flow:Et(n,t.flow,!0)}},minSTCut:(n,e)=>Gc(n,hh(n.s,Be(n,e.source,"source"),Be(n,e.sink,"sink"),n.rest)),stoerWagner:(n,e={})=>Gc(n,qh(n.s)),kargerMinCut:(n,e={})=>Gc(n,Hh(n.s,n.rest)),maximumBipartiteMatching:(n,e={})=>Bg(n,jh(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),greedyBipartiteMatching:(n,e={})=>Bg(n,AE(n.s,{...n.rest,left:pi(n,e.left),right:pi(n,e.right)})),commonNeighborsScore:(n,e)=>d3(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),adamicAdarScore:(n,e)=>sE(n.s,Be(n,e.source,"source"),Be(n,e.target,"target"),{directed:n.s.directed}),commonNeighborsPrediction:(n,e={})=>mi(n,Mh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),adamicAdarPrediction:(n,e={})=>mi(n,Fh(n.s,{...n.rest,directed:n.s.directed,uniquePairs:!0})),commonNeighborsForPairs:(n,e)=>Array.from(rE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),adamicAdarForPairs:(n,e)=>Array.from(iE(n.s,Qn(n,e.pairs,"pairs"),{directed:n.s.directed})),topCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,oE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},topAdamicAdarCandidatesForNode:(n,e)=>{const t=e.candidates===void 0?void 0:Gt(n.cs,e.candidates);return mi(n,aE(n.s,Be(n,e.root,"root"),{...n.rest,topK:Fg(e),candidates:t,directed:n.s.directed}))},evaluateCommonNeighbors:(n,e)=>Uh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),evaluateAdamicAdar:(n,e)=>Bh(n.s,Qn(n,e.edges,"edges"),Qn(n,e.nonEdges,"nonEdges"),{directed:n.s.directed}),compareAdamicAdarWithCommonNeighbors:(n,e)=>{const t=Qn(n,e.edges,"edges"),r=Qn(n,e.nonEdges,"nonEdges"),o={directed:n.s.directed};return{adamicAdar:Bh(n.s,t,r,o),commonNeighbors:Uh(n.s,t,r,o)}}};function $n(n){return`graphty${n.charAt(0).toUpperCase()}${n.slice(1)}`}const T_=Object.keys(Wc).map($n),Vc=["breadthFirstSearch","dijkstra","bellmanFord","allPairsShortestPath","pageRank","personalizedPageRank","eigenvectorCentrality","katzCentrality","hits","closenessCentrality","betweennessCentrality","edgeBetweennessCentrality","connectedComponents","weaklyConnectedComponents","triangleCount","labelPropagation","labelPropagationSynchronous"],O_=Vc.map(n=>`${$n(n)}Async`);function zg(n,e,t,r){const o=$n(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${o}: takes one options object; pass a weight function as { weight: fn }`);if(t.weight!==void 0&&S_.has(e))throw new Error(`${o}: this algorithm reads no edge weights; remove the weight option`);if(t.field!==void 0&&P_.has(e))throw new Error(`${o}: this algorithm has no per-element value to write; remove the field option`);const s=h_[o]??[];for(const[h,g]of Object.entries(t))if(g!==void 0&&!s.includes(h))throw new Error(`${o}: unknown option ${h}; the options are ${s.join(", ")}`);const i=t.directed??Ng.has(e),{mode:a}=t;if((a==="in"||a==="out")&&!i)throw new Error(`${o}: mode: "${a}" needs directed: true`);const c=hi(n,{directed:i,weight:t.weight}),l={...x_[e],...Object.fromEntries(Object.entries(t).filter(([h,g])=>!k_.has(h)&&g!==void 0))},u={name:o,cy:fi(n),cs:c,s:c.snapshot,field:t.field,weighted:t.weight!==void 0,rest:l,call:(h,...g)=>r[h](...g)},d=h=>{throw $_(h,e)};let f;try{f=Wc[e](u,t)}catch(h){d(h)}return{result:f instanceof Promise?f.catch(d):f,snapshot:c.snapshot}}function $_(n,e){if(!(n instanceof Error))return n;const t=$n(e),{code:r}=n;if(r==="E_NEEDS_UNDIRECTED"){const o=e==="connectedComponents"?", or call graphtyWeaklyConnectedComponents":"";n.message=`${t}: needs an undirected graph; leave out directed: true${o}`}else r==="E_NEEDS_DIRECTED"?n.message=`${t}: needs a directed graph; ${Ng.has(e)?"leave out directed: false":"pass directed: true"}`:n.message.startsWith(`${t}:`)||(n.message=`${t}: ${n.message}`);return n}function Gg(n,e,t={}){if($c($n(e),t?.gpu),t.gpu==="require"){const r=$n(e);throw new Error(Vc.includes(e)?`${r}: runs on the CPU; call ${r}Async for the GPU`:`${r}: has no GPU implementation and runs only on the CPU; leave out gpu: "require"`)}return zg(n,e,t,I_).result}async function Wg(n,e,t={}){$c(`${$n(e)}Async`,t?.gpu);const r=fi(n),o=await Cg(r,t.gpu);if(r.destroyed())throw cs();const s=o.gpu===null?null:__(o.gpu.accelerator);Dc(o,n.nodes().length);const{result:i,snapshot:a}=zg(n,e,t,f_(s?.accelerator??null)),c=bg(a);let l;try{l=await i}catch(d){throw r.destroyed()?cs():d}finally{c(),o.gpu!==null&&typeof t.weight=="function"&&o.gpu.accelerator.release(a)}const u=Lc(o,s?.used()??!1,"the options or the graph need the CPU implementation");return Object.assign(l,{backend:u})}function R_(n){for(const e of Object.keys(Wc)){const t=$n(e);n("collection",t,function(r){return Gg(this,e,r)}),n("core",t,function(r){return Gg(this.elements(),e,r)})}for(const e of Vc){const t=`${$n(e)}Async`;n("collection",t,function(r){return Wg(this,e,r)}),n("core",t,function(r){return Wg(this.elements(),e,r)})}}class D_ extends Error{constructor(e){super(`graphty: the core already has an element with id "${e}", so the new graph would merge into it; remove the existing elements (cy.elements().remove()) or add the graph to an empty core`),this.code="E_ID_TAKEN",this.name="IdTakenError",this.id=e}}function jc(n,e){if(n.destroyed())throw cs();for(const t of e)if(t.group==="nodes"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty())throw new D_(t.data.id);for(const t of e)t.group==="edges"&&t.data.id!==void 0&&n.getElementById(t.data.id).nonempty()&&delete t.data.id;return n.add(e)}function L_(n){const e=new Set(n.elements("[graphty_import]").map(r=>String(r.data("graphty_import"))));let t=e.size+1;for(;e.has(String(t));)t++;return String(t)}function M_(n,e,t){let r=0;e.forEach((o,s)=>{const i=n[r];if(i?.id()!==o.data.id)return;r++;const a=t[s];a!=null&&i.style(a)})}function U_(n){n("core","graphtyGenerate",async function(t,r){const{generateElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyGenerate"),s=o(t,r);return{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyDataset",async function(t,r){const{datasetElements:o}=await as(Promise.resolve().then(()=>I0),"graphtyDataset"),s=await o(t,r);return r?.signal?.throwIfAborted(),{elements:jc(this,s.elements),directed:s.directed}}),n("core","graphtyImport",async function(t,r,o){const{importElements:s}=await as(vu("io.js"),"graphtyImport"),i=o?.styles!==void 0&&o.styles!==!1,a=await s(t,r,{...o,...i&&o.importId===void 0?{importId:L_(this)}:{}}),c=o?.applyStyles===!0&&a.stylesheet!==void 0,l=jc(this,a.elements);c&&a.bypass!==void 0&&M_(l,a.elements,a.bypass);const u=this.style();if(c&&a.stylesheet!==void 0&&u!==void 0){let d=u;for(const f of a.stylesheet)d=d.selector(f.selector).style(f.style);d.update()}return{elements:l,directed:a.directed,format:a.format,report:a.report,...a.stylesheet===void 0?{}:{stylesheet:a.stylesheet}}});const e=async(t,r,o)=>{const{exportElements:s}=await as(vu("io.js"),"graphtyExport");return s(t,r,o)};n("core","graphtyExport",function(t,r){return e(this.elements(),t,r)}),n("collection","graphtyExport",function(t,r){return e(this,t,r)})}function F_(n,e,t,r){const{positions:o,dim:s,n:i}=n,a=new Float32Array(3*i),c=[0,0,0];for(let l=0;l<i;l++)for(let u=0;u<3;u++)a[3*l+u]=u<s?o[s*l+u]*e+c[u]:c[u];return a}function B_(n,e,t){const r=new Float64Array(t),o=new Float64Array(t);for(let s=0;s<e*t;s++){const i=n[s];Number.isNaN(i)||(r[s%t]+=i,o[s%t]++)}for(let s=0;s<t;s++)r[s]=o[s]>0?r[s]/o[s]:0;return r}function z_(n,e,t,r){let o=0;for(let s=0;s<e;s++){let i=0;for(let a=0;a<t;a++){const c=n[t*s+a]-r[a];Number.isNaN(c)||(i+=c*c)}o=Math.max(o,Math.sqrt(i))}return o}function Jn(n,e,t=1,r){const o=Math.floor(n.length/e),s=B_(n,o,e),i=z_(n,o,e,s),a=i>0?t/i:0;for(let c=0;c<o*e;c++){const l=n[c],u=r?.[c%e]??0;Number.isNaN(l)||(n[c]=a===0?u:(l-s[c%e])*a+u)}return n}const qc=34359738337,G_=185852,W_=1;let Vg=class{constructor(e){this.seed=e===null||e===0||Number.isNaN(e)?Math.floor(Math.random()*1e6):e,this.state=this.seed%qc}next(){return this.state=(G_*this.state+W_)%qc,this.state/qc}};function V_(n){const e=[0,0,0];if(n===null)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function bi(n,e,t,r,o,s,i){const a=n.nodeCount;if(r!==2&&r!==3)throw new RangeError(`dim must be 2 or 3, got ${String(r)}`);if(e.length!==3*a)throw new RangeError(`positions has ${e.length} entries, expected ${3*a}`);if(!Number.isFinite(o)||o<=0)throw new RangeError(`scale must be a finite number > 0, got ${o}`);const c=V_(s),l=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];let d=0,f=0;for(let y=0;y<a;y++){let b=!0;for(let v=0;v<r;v++){const A=e[3*y+v];Number.isFinite(A)?(A<l[v]&&(l[v]=A),A>u[v]&&(u[v]=A)):b=!1}b?d++:f++}if(f===0)return;const h=i==="fr"?0:-1,g=1,w=[h,h,h],p=[g,g,g];if(d>0){for(let y=0;y<r;y++)if(Number.isFinite(l[y])&&Number.isFinite(u[y])&&(w[y]=(l[y]-c[y])/o,p[y]=(u[y]-c[y])/o,w[y]===p[y])){const b=(g-h)/2;w[y]-=b,p[y]+=b}}const m=new Vg(t);for(let y=0;y<a;y++){let b=!1;for(let v=0;v<r;v++)Number.isFinite(e[3*y+v])||(b=!0);if(b){for(let v=0;v<r;v++){const A=3*y+v;if(!Number.isFinite(e[A])){const E=m.next(),I=w[v]+E*(p[v]-w[v]);e[A]=I*o+c[v]}}r===2&&(e[3*y+2]=c[2])}}}const jg=new WeakMap;function j_(n){if(n!=null)return typeof n=="number"?n:typeof n=="string"?Number(n):Number.NaN}function co(n,e=null){if(vv(n)){if(!n.directed)return n;const r=jg.get(n);if(r!==void 0)return r;const o=n.toUndirected().snapshot;return jg.set(n,o),o}const t=new oi({directed:!1,weighted:"auto"});if(Array.isArray(n))t.addNodes(n);else{t.addNodes(n.nodes());for(const[r,o]of n.edges()){const s=e!==null&&n.getEdgeData!==void 0?n.getEdgeData(r,o,e):void 0;t.addEdge(r,o,j_(s))}}return t.freeze()}function ze(n,e,t){return Object.assign(n,{code:e,params:t})}function en(n,e){const t=e.dim??2;if(t!==2&&t!==3)throw ze(new Error(`dim must be 2 or 3, got ${String(t)}`),"E_BAD_OPTION",{option:"dim",value:t});const r=Array.from({length:t},(o,s)=>e.center?.[s]??0);return{n:n.nodeCount,dim:t,scale:e.scale??1,center:r}}function Wt(n,e,t){return{positions:Float32Array.from(n),dim:e,n:t}}function Rn(n,e,t){if(e===2)return n;const r=n.length/2,o=new Float64Array(3*r);for(let s=0;s<r;s++)o[3*s]=n[2*s],o[3*s+1]=n[2*s+1],o[3*s+2]=Number.isNaN(n[2*s])?Number.NaN:t[2];return o}function qg(n){const e=n??2;if(e!==2&&e!==3)throw ze(new RangeError(`dim must be 2 or 3, got ${String(e)}`),"E_BAD_OPTION",{option:"dim",value:e});return e}function q_(n,e,t){const r=n.nodeCount;if(e==null)return new Float32Array(3*r).fill(Number.NaN);if(e.length!==t*r)throw ze(new RangeError(`pos has ${e.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:e.length,expected:t*r});return F_({positions:e,dim:t,n:r},1)}function H_(n,e={}){const{scaling:t=1,a:r=1.1,maxIter:o=1e3}=e;if(r<=1)throw ze(new Error("The parameter a should be larger than 1"),"E_BAD_OPTION",{option:"a",value:r});const s=co(n),i=qg(e.dim),a=s.nodeCount,c=Float64Array.from(q_(s,e.pos,i));bi(s,c,e.seed??null,i,1,null,"fr");const l=new Float64Array(i*a);for(let b=0;b<a;b++)for(let v=0;v<i;v++)l[i*b+v]=c[3*b+v];const{rowPtr:u,colIdx:d}=s,f=t*Math.sqrt(a),h=.001,g=1e-6,w=new Float64Array(i*a),p=new Float64Array(i),m=new Int32Array(a);let y=g+1;for(let b=0;y>g&&b<o;b++){w.fill(0);for(let v=0;v<a;v++){for(let A=u[v];A<u[v+1];A++)m[d[A]]=v+1;for(let A=0;A<a;A++){if(v===A)continue;let E=0;for(let N=0;N<i;N++)p[N]=l[i*v+N]-l[i*A+N],E+=p[N]*p[N];const I=Math.sqrt(E)||.01,k=m[A]===v+1?r:1;for(let N=0;N<i;N++)w[i*v+N]+=f/I*p[N]-k*p[N]}}y=0;for(let v=0;v<a;v++){let A=0;for(let E=0;E<i;E++)l[i*v+E]+=w[i*v+E]*h,A+=w[i*v+E]*w[i*v+E];y+=Math.sqrt(A)}}return(e.scale!==void 0||e.center!==void 0)&&Jn(l,i,e.scale??1,e.center),{positions:Float32Array.from(l),dim:i,n:a}}function Hc(n,e,t,r,o,s,i="subsets"){if(r!=="vertical"&&r!=="horizontal")throw ze(new Error("align must be either vertical or horizontal"),"E_BAD_OPTION",{option:"align",value:r});const a=new Float64Array(2*n).fill(Number.NaN);if(e.forEach((c,l)=>{for(let u=0;u<c.length;u++){const d=c[u];if(!Number.isInteger(d)||d<0||d>=n)throw ze(new Error(`layer node index ${String(d)} is not a node of the graph`),"E_BAD_NODE",{option:i,index:d});[a[2*d],a[2*d+1]]=t(l,e.length,u,c.length)}}),r==="vertical")return Jn(a,2,o,s);Jn(a,2,o,[s[1],s[0]]);for(let c=0;c<n;c++)[a[2*c],a[2*c+1]]=[a[2*c+1],a[2*c]];return a}const Hg=(n,e,t,r)=>[n-(e-1)/2,t-(r-1)/2];function Kg(n,e,t){const r=n.nodes.get(e);if(r===null)throw ze(new Error(`${t} names node column "${e}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:t,column:e});if(r.dtype!=="u32"&&r.dtype!=="dict")throw ze(new Error(`${t} column "${e}" must be u32 or dict, not ${r.dtype}`),"E_COLUMN_TYPE",{option:t,column:e,dtype:r.dtype,expected:["u32","dict"]});const o=r.dtype==="u32"?r.data:r.codes,s=new Map;for(let i=0;i<n.nodeCount;i++)if(r.isSet(i)){const a=s.get(o[i]);a===void 0?s.set(o[i],[i]):a.push(i)}return[...s.keys()].sort((i,a)=>i-a).map(i=>s.get(i)??[])}function K_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{subsets:i="subset",align:a="vertical"}=e,c=typeof i=="string"?Kg(n,i,"subsets"):i.map(l=>ss(n,l));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Y_(n,e){const t=n.nodeCount;if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`start node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"start",index:e});const r=new Uint8Array(t);r[e]=1;let o=1;const s=[[e]];for(let i=s[0];;){const a=[];for(const c of i)for(let l=n.rowPtr[c];l<n.rowPtr[c+1];l++){const u=n.colIdx[l];r[u]===0&&(r[u]=1,a.push(u))}if(a.length===0)break;o+=a.length,s.push(a),i=a}if(o<t)throw Object.assign(new Error("bfs_layout didn't include all nodes. Graph may be disconnected."),{code:"E_NOT_CONNECTED",params:{nodeCount:t,reached:o}});return s}function X_(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{start:i=0,align:a="vertical"}=e,c=t===0?[]:Y_(co(n),xe(n,i));return Wt(Rn(Hc(t,c,Hg,a,o,s),r,s),r,t)}function Q_(n,e,t,r,o,s,i){const a=r;return Hc(n,[e,t],(c,l,u,d)=>[c*a-a/2,u/d-.5],o,s,i)}function J_(n,e){const t=typeof e=="string"||e instanceof Uint32Array?e:Df(n,e);if(typeof t!="string"){if(t.length<Math.ceil(n.nodeCount/32))throw ze(new Error(`top mask has ${t.length} words; ${n.nodeCount} nodes need ${Math.ceil(n.nodeCount/32)}`),"E_BAD_OPTION",{option:"top",length:t.length,expected:Math.ceil(n.nodeCount/32)});return o=>(t[o>>>5]>>>(o&31)&1)===1}const r=n.nodes.get(t);if(r===null)throw ze(new Error(`top names node column "${t}", which the snapshot does not hold`),"E_UNKNOWN_COLUMN",{option:"top",column:t});if(r.dtype!=="bool")throw ze(new Error(`top column "${t}" must be bool, not ${r.dtype}`),"E_COLUMN_TYPE",{option:"top",column:t,dtype:r.dtype,expected:["bool"]});return o=>r.isSet(o)&&(r.data[o>>>5]>>>(o&31)&1)===1}function Yg(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{top:i,align:a="vertical",aspectRatio:c=1.3333333333333333}=e,l=i===void 0?f=>f%2===0:J_(n,i),u=[],d=[];for(let f=0;f<t;f++)(l(f)?u:d).push(f);return Wt(Rn(Q_(t,u,d,c,a,o,s),r,s),r,t)}const ds={zeros:function(n){return typeof n=="number"?new Array(n).fill(0):n.length===1?new Array(n[0]).fill(0):new Array(n[0]).fill(0).map(()=>this.zeros(n.slice(1)))},ones:function(n){return typeof n=="number"?new Array(n).fill(1):n.length===1?new Array(n[0]).fill(1):new Array(n[0]).fill(1).map(()=>this.ones(n.slice(1)))},linspace:function(n,e,t){if(t===1)return[n];const r=(e-n)/(t-1);return Array.from({length:t},(o,s)=>n+s*r)},array:function(n){return Array.isArray(n)?[...n]:[n]},repeat:function(n,e){const t=[];for(let r=0;r<e;r++)t.push(...ds.array(n));return t},mean:function(n,e=null){if(e===null){const t=Array.isArray(n[0])?n.flat(1/0):n;return t.reduce((o,s)=>o+s,0)/t.length}if(e===0){const t=[],r=n;for(let o=0;o<r[0].length;o++){let s=0;for(let i=0;i<r.length;i++)s+=r[i][o];t.push(s/r.length)}return t}return n.map(t=>ds.mean(t))},add:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n+e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t+e[r]):n.map(t=>t+e):e.map(t=>n+t)},subtract:function(n,e){return!Array.isArray(n)&&!Array.isArray(e)?n-e:Array.isArray(n)?Array.isArray(e)?n.map((t,r)=>t-e[r]):n.map(t=>t-e):e.map(t=>n-t)},max:function(n){return Array.isArray(n)?Math.max(...n.flat(1/0)):n},min:function(n){return Array.isArray(n)?Math.min(...n.flat(1/0)):n},norm:function(n){return Math.sqrt(n.reduce((e,t)=>e+t*t,0))}};function Z_(n,e,t,r){const o=new Float64Array(n*e);if(n===1)o.set(r);else if(e===2){const s=ds.linspace(0,2*Math.PI,n+1);for(let i=0;i<n;i++)o[2*i]=yn(s[i])*t+r[0],o[2*i+1]=Jt(s[i])*t+r[1]}else{const s=(1+Math.sqrt(5))/2;for(let i=0;i<n;i++){const a=2*Math.PI*i/s,c=Of(1-2*(i+.5)/n);o[3*i]=Jt(c)*yn(a)*t+r[0],o[3*i+1]=Jt(c)*Jt(a)*t+r[1],o[3*i+2]=yn(c)*t+r[2]}}return o}function eI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Z_(t,r,o,s),r,t)}const ut=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1}),vi=.01,tI=1e-4,Xg=1e-8,xr=256,Qg=.9,nI=5,rI=1e4;function Jg(n,e,t){if(t.meta.components!==1)throw new RangeError(`node column "${e}" has ${t.meta.components} components; a node vector has one`);switch(t.dtype){case"f32":case"f64":{const r=n.nodes.gpuView(e);return r instanceof Float32Array?r:new Float32Array(r)}case"u32":case"i32":return new Float32Array(n.nodes.gpuView(e));case"u8":return new Float32Array(t.data);default:throw new TypeError(`node column "${e}" is ${t.dtype}, not numeric`)}}function oI(n,e,t){const r=e.nodeCount;if(n==null){const s=e.nodes.byRole("mass");if(s!==null)return Jg(e,s.meta.name,s);const i=new Float32Array(r);for(let a=0;a<r;a++)i[a]=t(a);return i}if(n instanceof Float32Array){if(n.length!==r)throw new RangeError(`the node vector has ${n.length} values, expected ${r}`);return n}if(typeof n=="string"){const s=e.nodes.get(n);if(s===null)throw new RangeError(`the option names node column "${n}", which the snapshot does not hold`);return Jg(e,n,s)}const o=new Float32Array(r);for(let s=0;s<r;s++){const i=n[e.ids.idOf(s)];o[s]=i===void 0?t(s):i}return o}function Zg(n,e){if(n===!0)return e.weights;if(n===!1||n===null||n===void 0)return null;const t=e.edges.get(n);if(t===null)throw new RangeError(`weight names edge column "${n}", which the snapshot does not hold`);if(t.meta.components!==1)throw new RangeError(`edge column "${n}" has ${t.meta.components} components; a weight column has one`);switch(t.dtype){case"f32":case"f64":case"u32":case"i32":{const r=Va(e,e.edges.gpuView(n));return r instanceof Float32Array?r:new Float32Array(r)}default:throw new TypeError(`edge column "${n}" is ${t.dtype}; a weight column is f32, f64, u32 or i32`)}}function Zn(n,e,t,r,o){if(e===void 0)return t;if(typeof e!="number"||!r(e))throw new RangeError(`ForceAtlas2Simulation: ${n} must be ${o}, got ${String(e)}`);return e}function Kc(n,e,t){if(e===void 0)return t;if(typeof e!="boolean")throw new TypeError(`ForceAtlas2Simulation: ${n} must be a boolean, got ${String(e)}`);return e}function sI(n){const e=[0,0,0];if(n===void 0)return e;if(n.length>3)throw new RangeError(`ForceAtlas2Simulation: center has ${n.length} components, at most 3 expected`);for(let t=0;t<n.length;t++){const r=n[t];if(typeof r!="number"||!Number.isFinite(r))throw new RangeError(`ForceAtlas2Simulation: center[${t}] is not finite`);e[t]=r}return e}function Ai(n){return Number.isInteger(n)&&n>=1}function iI(n){const e=n??{},t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`ForceAtlas2Simulation: dim must be 2 or 3, got ${String(t)}`);const r=e.compat??"paper";if(r!=="paper"&&r!=="networkx")throw new RangeError(`ForceAtlas2Simulation: compat must be "paper" or "networkx", got ${String(r)}`);return{maxIter:Zn("maxIter",e.maxIter,ut.maxIter,Ai,"an integer >= 1"),jitterTolerance:Zn("jitterTolerance",e.jitterTolerance,ut.jitterTolerance,o=>o>0,"> 0"),scalingRatio:Zn("scalingRatio",e.scalingRatio,ut.scalingRatio,o=>o>0,"> 0"),gravity:Zn("gravity",e.gravity,ut.gravity,o=>o>=0,">= 0"),strongGravity:Kc("strongGravity",e.strongGravity,ut.strongGravity),distributedAction:Kc("distributedAction",e.distributedAction,ut.distributedAction),linlog:Kc("linlog",e.linlog,ut.linlog),nodeMass:e.nodeMass??null,weight:e.weight??null,dim:t,scale:Zn("scale",e.scale,ut.scale,o=>Number.isFinite(o)&&o>0,"a finite number > 0"),center:sI(e.center),settleThreshold:Zn("settleThreshold",e.settleThreshold,ut.settleThreshold,o=>o>=0,">= 0"),settleWindow:Zn("settleWindow",e.settleWindow,ut.settleWindow,Ai,"an integer >= 1"),iterationsPerStep:Zn("iterationsPerStep",e.iterationsPerStep,ut.iterationsPerStep,Ai,"an integer >= 1"),compat:r,seed:e.seed??null}}function Yc(n){return{attraction:new Float64Array(3*n),force:new Float64Array(3*n),swing:new Float64Array(n),traction:new Float64Array(n),sumX:new Float64Array(n),sumY:new Float64Array(n),sumZ:new Float64Array(n),sumW:new Float64Array(n),disp:new Float64Array(n),free:new Float64Array(n)}}function ew(n){for(let e=xr/2;e>0;e=Math.floor(e/2))for(let t=0;t<e;t++)n[t]=n[t]+n[t+e];return n[0]}function er(n,e){const t=Math.ceil(e/xr),r=new Float64Array(t),o=new Float64Array(xr);for(let s=0;s<t;s++){for(let i=0;i<xr;i++){const a=s*xr+i;o[i]=a<e?n[a]:0}r[s]=ew(o)}return r}function tr(n){const e=new Float64Array(xr);for(let t=0;t<n.length;t++){const r=t%xr;e[r]=e[r]+n[t]}return ew(e)}function Dn(n,e,t){return Math.sqrt(n*n+e*e+t*t)}function tw(n){let e=n>>>0;return e=(e^e>>>16)>>>0,e=Math.imul(e,2146121005)>>>0,e=(e^e>>>15)>>>0,e=Math.imul(e,2221713035)>>>0,e=(e^e>>>16)>>>0,e}function aI(n,e){const t=Math.min(n,e),r=Math.max(n,e);return tw((Math.imul(t,2654435769)>>>0^r)>>>0)}function nw(n){return(n>>>8)*5960464477539063e-23}function rw(n,e,t){const r=aI(n,e),o=6.283185307179586*nw(r);let s;if(t===2)s=[yn(o),Jt(o),0];else{const i=2*nw(tw((r^1540483477)>>>0))-1,a=Math.sqrt(Math.max(0,1-i*i));s=[a*yn(o),a*Jt(o),i]}return n>e?[-s[0],-s[1],-s[2]]:s}function cI(n,e,t,r,o,s){const i=n,a=s,c=.05*Math.sqrt(i),l=Math.sqrt(c),u=10,d=Math.max(t,1e-30),f=Math.min(u,c*t/(i*i));let h=a*Math.max(l,f),g=o;e>2*d&&(g>.05&&(g=g*.5),h=Math.max(h,a));const w=e===0?1e30:h*g*t/e;return e>h*t?g>.05&&(g=g*.7):r<1e3&&(g=g*1.3),{speed:r+Math.min(w-r,.5*r),speedEfficiency:g}}function lI(n,e,t,r){for(let o=0;o<t;o++){if(n[o]===e[o])continue;const s=Math.min(r,o*32+32);for(let i=o*32;i<s;i++)if(_e(n,i)&&!_e(e,i))return!0}return!1}class uI{constructor(e){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.weights=null,this.mass=new Float64Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.fixed=null,this.scratch=Yc(0),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.settledCountValue=0,this.iterationsDoneValue=0,this.centroid=[0,0,0],this.pending=null,this.options=iI(e),this.dim=this.options.dim,this.swingMode=this.options.compat==="networkx"?1:0,this.gravityCenter=this.options.compat==="networkx"?1:0}get settled(){return this.state!=="loaded"?!1:this.n===0||this.iterationsDoneValue>=this.options.maxIter||this.settledCountValue>=this.options.settleWindow}get iterationsDone(){return this.iterationsDoneValue}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("ForceAtlas2Simulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new Error(`ForceAtlas2Simulation: positions.length ${t.length} !== 3 x ${r}`);const o=e.outDegree(),s=oI(this.options.nodeMass,e,p=>o[p]+1),i=Zg(this.options.weight,e),a=new Float64Array(r);for(let p=0;p<r;p++)if(a[p]=s[p],!(a[p]>0))throw new Error(`ForceAtlas2Simulation: mass[${p}] must be positive`);const c=i===null?null:Float64Array.from(i);r!==this.n&&(this.fixed=null),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.mass=a,this.weights=c,this.owner=t;const{scale:l,center:u,seed:d}=this.options;bi(e,t,d,this.dim,l,u,"fa2");const[f,h,g]=u,w=new Float64Array(3*r);for(let p=0;p<r;p++)w[3*p]=(t[3*p]-f)/l,w[3*p+1]=(t[3*p+1]-h)/l,w[3*p+2]=this.dim===2?0:(t[3*p+2]-g)/l;this.positions=w,this.oldForce=new Float64Array(3*r),this.scratch=Yc(r),this.speedValue=1,this.speedEfficiencyValue=1,this.swingValue=1,this.tractionValue=1,this.pending=null,this.writeInitialStatistics(),this.state="loaded",this.reheat()}step(e=this.options.iterationsPerStep){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed");if(this.state==="created")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)");if(!Ai(e))throw new RangeError(`ForceAtlas2Simulation: iterations must be an integer >= 1, got ${String(e)}`);if(this.settled)return;let t=0;for(;t<e&&!this.settled;)this.iterate(),this.iterationsDoneValue+=1,t+=1;this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`ForceAtlas2Simulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);const o=this.fixed,s=o!==null&&lI(o,e,r,t),i=new Uint32Array(r);i.set(e.subarray(0,r)),this.fixed=i,s&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s,owner:i}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`ForceAtlas2Simulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("ForceAtlas2Simulation: setPosition: coordinates must be finite");i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o;const{scale:a}=this.options,[c,l,u]=this.options.center;this.positions[3*e]=(i[3*e]-c)/a,this.positions[3*e+1]=(i[3*e+1]-l)/a,this.positions[3*e+2]=this.dim===2?0:(i[3*e+2]-u)/a,this.reheat()}reheat(){this.assertNotDisposed(),this.iterationsDoneValue=0,this.settledCountValue=0,this.swingMode===1&&(this.swingValue=1,this.tractionValue=1)}dispose(){this.state="disposed",this.owner=new Float32Array(0),this.scratch=Yc(0),this.pending=null,this.positions=new Float64Array(0),this.oldForce=new Float64Array(0),this.mass=new Float64Array(0),this.weights=null,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null,this.n=0}assertNotDisposed(){if(this.state==="disposed")throw new Error("ForceAtlas2Simulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("ForceAtlas2Simulation: not loaded (call load() first)")}isFixed(e){return this.fixed!==null&&_e(this.fixed,e)}writeBack(){const{n:e,owner:t,positions:r}=this,{scale:o}=this.options,[s,i,a]=this.options.center;for(let c=0;c<e;c++)this.isFixed(c)||(t[3*c]=r[3*c]*o+s,t[3*c+1]=r[3*c+1]*o+i,t[3*c+2]=this.dim===2?a:r[3*c+2]*o+a)}writeInitialStatistics(){const{n:e,positions:t}=this,r=[0,0,0];for(let o=0;o<e;o++)for(let s=0;s<3;s++)r[s]+=t[3*o+s];e===0?this.centroid=[0,0,0]:this.centroid=[r[0]/e,r[1]/e,r[2]/e],this.settledCountValue=0}foldTotals(e){return{sum:[tr(e.sumX),tr(e.sumY),tr(e.sumZ)],sumSq:tr(e.sumW),disp:tr(e.disp),free:tr(e.free)}}fold(e){const t=this.foldTotals(e),r=this.n,o=Math.sqrt(Math.max(t.sumSq,0)/r),s=t.free===0?0:t.disp/t.free;this.centroid=[t.sum[0]/r,t.sum[1]/r,t.sum[2]/r],this.settledCountValue=s<=this.options.settleThreshold*o?this.settledCountValue+1:0}iterate(){const{n:e,scratch:t}=this;this.pending!==null&&this.fold(this.pending);const{positions:r,mass:o,rowPtr:s,colIdx:i,weights:a,oldForce:c}=this,{scalingRatio:l,gravity:u,linlog:d,distributedAction:f,strongGravity:h}=this.options,{attraction:g,force:w,swing:p,traction:m,sumX:y,sumY:b,sumZ:v,sumW:A,disp:E,free:I}=t;for(let R=0;R<e;R++){let D=0,U=0,B=0;const V=r[3*R],W=r[3*R+1],q=r[3*R+2];for(let K=s[R];K<s[R+1];K++){const X=i[K];if(X===R)continue;const H=a===null?1:a[K],Y=r[3*X]-V,ee=r[3*X+1]-W,Z=r[3*X+2]-q;let J=H;if(d){const ce=Math.max(Dn(Y,ee,Z),vi);J=H*Ge(1+ce)/ce}D=D+Y*J,U=U+ee*J,B=B+Z*J}f&&(D=D/o[R],U=U/o[R],B=B/o[R]),g[3*R]=D,g[3*R+1]=U,g[3*R+2]=B}p.fill(0),m.fill(0);const k=this.centroid[0],N=this.centroid[1],C=this.centroid[2];for(let R=0;R<e;R++){const D=r[3*R],U=r[3*R+1],B=r[3*R+2],V=o[R];let W=0,q=0,K=0;for(let he=0;he<e;he++){if(he===R)continue;const ge=o[he],me=D-r[3*he],De=U-r[3*he+1],Ne=B-r[3*he+2];let He=me*me+De*De+Ne*Ne;if(He<Xg){const Ft=rw(R,he,this.dim),Nt=l*V*ge/vi;W=W+Ft[0]*Nt,q=q+Ft[1]*Nt,K=K+Ft[2]*Nt;continue}He=Math.max(He,tI);const mt=l*V*ge/He;W=W+me*mt,q=q+De*mt,K=K+Ne*mt}let X=0,H=0,Y=0;const ee=this.gravityCenter===0?D-k:D,Z=this.gravityCenter===0?U-N:U,J=this.gravityCenter===0?B-C:B,ce=-u*V;if(h)X=ce*ee,H=ce*Z,Y=ce*J;else{const he=Dn(ee,Z,J);he>vi&&(X=ce*ee/he,H=ce*Z/he,Y=ce*J/he)}W=W+X,q=q+H,K=K+Y;const de=g[3*R]+W,ne=g[3*R+1]+q,ve=g[3*R+2]+K;w[3*R]=de,w[3*R+1]=ne,w[3*R+2]=ve;const ue=c[3*R],we=c[3*R+1],Xe=c[3*R+2];this.swingMode===1?(p[R]=V*Dn(D-de,U-ne,B-ve),m[R]=.5*V*Dn(D+de,U+ne,B+ve)):this.isFixed(R)||(p[R]=V*Dn(de-ue,ne-we,ve-Xe),m[R]=.5*V*Dn(de+ue,ne+we,ve+Xe))}const O=tr(er(p,e)),T=tr(er(m,e));let $=O,L=T;this.swingMode===1&&($=this.swingValue+O,L=this.tractionValue+T);const F=cI(e,$,L,this.speedValue,this.speedEfficiencyValue,this.options.jitterTolerance);this.speedValue=F.speed,this.speedEfficiencyValue=F.speedEfficiency,this.swingValue=$,this.tractionValue=L;const M=this.speedValue;E.fill(0),I.fill(0);for(let R=0;R<e;R++){const D=w[3*R],U=w[3*R+1],B=w[3*R+2],V=o[R];let W=V*Dn(D,U,B);this.swingMode===0&&(W=V*Dn(D-c[3*R],U-c[3*R+1],B-c[3*R+2]));const q=M/(1+Math.sqrt(M*W)),K=this.isFixed(R),X=K?0:D*q,H=K?0:U*q;let Y=K?0:B*q;this.dim===2&&(Y=0);const ee=r[3*R]+X,Z=r[3*R+1]+H,J=r[3*R+2]+Y;r[3*R]=ee,r[3*R+1]=Z,r[3*R+2]=J,this.swingMode===0&&(c[3*R]=D,c[3*R+1]=U,c[3*R+2]=B);const ce=ee-k,de=Z-N,ne=J-C;y[R]=ee,b[R]=Z,v[R]=J,A[R]=ce*ce+de*de+ne*ne,K||(E[R]=Dn(X,H,Y),I[R]=1)}this.pending={sumX:er(y,e),sumY:er(b,e),sumZ:er(v,e),sumW:er(A,e),disp:er(E,e),free:er(I,e)}}}const fs=.1,dI=50,fI=.1,hI=.7;function gI(n){const e=[0,0,0];if(n===void 0)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new RangeError(`center[${t}] is not finite`);e[t]=r}return e}function Ei(n,e,t,r,o){if(!Number.isFinite(e)||e<t||e>r||o&&!Number.isInteger(e))throw new RangeError(`FruchtermanReingoldSimulation: ${n} must be ${o?"an integer":"a finite number"} in [${t}, ${r}], got ${e}`);return e}class wI{constructor(e={}){this.state="created",this.n=0,this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.owner=new Float32Array(0),this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.fixed=null,this.k=0,this.dt=0,this.t=fs,this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0,this.pendingEnergy=null,this.iterationsDoneValue=0,this.settledCountValue=0,this.settledValue=!1,this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;const t=e.dim??ut.dim;if(t!==2&&t!==3)throw new RangeError(`FruchtermanReingoldSimulation: dim must be 2 or 3, got ${String(t)}`);this.dim=t;const r=e.scale??ut.scale;if(!Number.isFinite(r)||r<=0)throw new RangeError(`FruchtermanReingoldSimulation: scale must be a finite number > 0, got ${r}`);this.scale=r,this.center=gI(e.center),this.seed=e.seed??null;const o=e.k??null;if(o===null||Number.isNaN(o)||o===0)this.kOption=null;else{if(!Number.isFinite(o)||o<0)throw new RangeError(`FruchtermanReingoldSimulation: k must be null, 0 or a finite number > 0, got ${o}`);this.kOption=o}const s=e.cooling??"linear";if(s!=="linear"&&s!=="adaptive")throw new RangeError(`FruchtermanReingoldSimulation: cooling must be "linear" or "adaptive", got ${String(s)}`);this.adaptive=s==="adaptive",this.iterations=Ei("iterations",e.iterations??(this.adaptive?rI:dI),0,Number.MAX_SAFE_INTEGER,!0),this.settleThreshold=Ei("settleThreshold",e.settleThreshold??ut.settleThreshold,0,Number.POSITIVE_INFINITY,!1),this.settleWindow=Ei("settleWindow",e.settleWindow??ut.settleWindow,1,Number.MAX_SAFE_INTEGER,!0),this.iterationsPerStep=Ei("iterationsPerStep",e.iterationsPerStep??ut.iterationsPerStep,1,Number.MAX_SAFE_INTEGER,!0),this.fixedOption=e.fixed??null}get settled(){return this.settledValue}get iterationsDone(){return this.iterationsDoneValue}get settledCount(){return this.settledCountValue}get meanDisplacement(){return this.meanDisplacementValue}get rmsRadius(){return this.rmsRadiusValue}get temperature(){return this.t}load(e,t){if(this.assertNotDisposed(),e.directed)throw new Error("FruchtermanReingoldSimulation: the snapshot must be undirected (pass toUndirected().snapshot)");const r=e.nodeCount;if(t.length!==3*r)throw new RangeError(`FruchtermanReingoldSimulation: positions has ${t.length} entries, expected ${3*r}`);const o=this.resolveFixed(e,r);r!==this.n&&(this.positions=new Float64Array(3*r),this.displacement=new Float64Array(3*r)),this.n=r,this.rowPtr=e.rowPtr,this.colIdx=e.colIdx,this.owner=t,this.fixed=o,bi(e,t,this.seed,this.dim,this.scale,this.center,"fr");const s=this.positions,[i,a,c]=this.center,{scale:l}=this;for(let u=0;u<r;u++)s[3*u]=(t[3*u]-i)/l,s[3*u+1]=(t[3*u+1]-a)/l,s[3*u+2]=this.dim===2?0:(t[3*u+2]-c)/l;this.k=this.kOption??1/Math.sqrt(r),this.dt=fs/(this.iterations+1),this.t=fs,this.resetAdaptive(),this.pendingEnergy=null,this.writeInitialStatistics(),this.iterationsDoneValue=0,this.settledCountValue=0,this.state="loaded",this.settledValue=r===0||this.computeSettled()}step(e=this.iterationsPerStep){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded");if(!Number.isInteger(e)||e<1)throw new RangeError(`FruchtermanReingoldSimulation: step(${e}): an integer >= 1 is required`);if(this.settledValue)return;let t=0;for(;t<e&&!this.settledValue;)this.iterate(),t++,this.iterationsDoneValue++,this.settledValue=this.computeSettled();this.writeBack()}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw new RangeError(`FruchtermanReingoldSimulation: setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);let o=!1;const s=this.fixed;if(s!==null)for(let i=0;i<t&&!o;i++)_e(s,i)&&!_e(e,i)&&(o=!0);this.fixed=new Uint32Array(e.subarray(0,r)),o&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s}=this;if(!Number.isInteger(e)||e<0||e>=s)throw new RangeError(`FruchtermanReingoldSimulation: setPosition(${e}): index out of range [0, ${s})`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw new RangeError("FruchtermanReingoldSimulation: setPosition: coordinates must be finite");const{owner:i,positions:a,scale:c}=this,[l,u,d]=this.center;i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o,a[3*e]=(t-l)/c,a[3*e+1]=(r-u)/c,a[3*e+2]=this.dim===2?0:(o-d)/c,this.reheat()}reheat(){this.assertNotDisposed(),this.settledCountValue=0,this.adaptive?(this.iterationsDoneValue=0,this.t=fs,this.resetAdaptive()):(this.iterationsDoneValue=Math.floor(hI*this.iterations),this.t=fs-this.dt*this.iterationsDoneValue),this.state==="loaded"&&(this.settledValue=this.n===0||this.computeSettled())}dispose(){this.state="disposed",this.n=0,this.positions=new Float64Array(0),this.displacement=new Float64Array(0),this.owner=new Float32Array(0),this.rowPtr=new Uint32Array(1),this.colIdx=new Uint32Array(0),this.fixed=null}iterate(){this.adaptive&&this.pendingEnergy!==null&&this.updateAdaptive(this.pendingEnergy);const{n:e,k:t,t:r,positions:o,displacement:s,rowPtr:i,colIdx:a,fixed:c}=this;s.fill(0);for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=b+1;I<e;I++){const k=v-o[3*I],N=A-o[3*I+1],C=E-o[3*I+2],O=k*k+N*N+C*C;let T,$,L;if(O<Xg){const F=rw(b,I,this.dim),M=t*t/vi;T=F[0]*M,$=F[1]*M,L=F[2]*M}else{const F=Math.sqrt(O),M=t*t/F;T=k/F*M,$=N/F*M,L=C/F*M}s[3*b]+=T,s[3*b+1]+=$,s[3*b+2]+=L,s[3*I]-=T,s[3*I+1]-=$,s[3*I+2]-=L}}for(let b=0;b<e;b++){const v=o[3*b],A=o[3*b+1],E=o[3*b+2];for(let I=i[b];I<i[b+1];I++){const k=a[I],N=v-o[3*k],C=A-o[3*k+1],O=E-o[3*k+2],T=Math.sqrt(N*N+C*C+O*O)||fI,$=T*T/t;s[3*b]-=N/T*$,s[3*b+1]-=C/T*$,s[3*b+2]-=O/T*$}}const[l,u,d]=this.centroid;let f=0,h=0,g=0,w=0,p=0,m=0,y=0;for(let b=0;b<e;b++){if(c===null||!_e(c,b)){const C=s[3*b],O=s[3*b+1],T=s[3*b+2],$=C*C+O*O+T*T,L=Math.sqrt($);y+=$;const F=Math.min(L,r);L!==0&&(o[3*b]+=C/L*F,o[3*b+1]+=O/L*F,o[3*b+2]+=T/L*F),p+=F,m++}const v=o[3*b],A=o[3*b+1],E=o[3*b+2];f+=v,h+=A,g+=E;const I=v-l,k=A-u,N=E-d;w+=I*I+k*k+N*N}this.adaptive?this.pendingEnergy=y:this.t-=this.dt,this.centroid=[f/e,h/e,g/e],this.rmsRadiusValue=Math.sqrt(Math.max(w,0)/e),this.meanDisplacementValue=m===0?0:p/m,this.settledCountValue=this.meanDisplacementValue<=this.settleThreshold*this.rmsRadiusValue?this.settledCountValue+1:0}resetAdaptive(){this.previousEnergy=Number.POSITIVE_INFINITY,this.progress=0}updateAdaptive(e){e<this.previousEnergy?(this.progress++,this.progress>=nI&&(this.progress=0,this.t/=Qg)):(this.progress=0,this.t*=Qg),this.previousEnergy=e}writeBack(){const{n:e,owner:t,positions:r,scale:o,fixed:s}=this,[i,a,c]=this.center;for(let l=0;l<e;l++)s!==null&&_e(s,l)||(t[3*l]=r[3*l]*o+i,t[3*l+1]=r[3*l+1]*o+a,t[3*l+2]=r[3*l+2]*o+c)}writeInitialStatistics(){const{n:e,positions:t}=this;if(e===0){this.centroid=[0,0,0],this.rmsRadiusValue=0,this.meanDisplacementValue=0;return}let r=0,o=0,s=0;for(let a=0;a<e;a++)r+=t[3*a],o+=t[3*a+1],s+=t[3*a+2];r/=e,o/=e,s/=e;let i=0;for(let a=0;a<e;a++){const c=t[3*a]-r,l=t[3*a+1]-o,u=t[3*a+2]-s;i+=c*c+l*l+u*u}this.centroid=[r,o,s],this.rmsRadiusValue=Math.sqrt(i/e),this.meanDisplacementValue=0}computeSettled(){return this.iterationsDoneValue>=this.iterations||this.settledCountValue>=this.settleWindow}resolveFixed(e,t){const r=Math.ceil(t/32),o=this.fixedOption;if(typeof o=="string"){const i=e.nodes.get(o);if(i===null)throw new RangeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which the snapshot does not hold`);if(i.dtype!=="bool")throw new TypeError(`FruchtermanReingoldSimulation: fixed names node column "${o}", which is ${i.dtype}, not bool`);return new Uint32Array(i.data.subarray(0,r))}if(o!==null){if(o.length<r)throw new RangeError(`FruchtermanReingoldSimulation: the fixed mask has ${o.length} words, ${r} needed for ${t} nodes`);return new Uint32Array(o.subarray(0,r))}const s=e.nodes.byRole("fixed");return s!==null&&s.dtype==="bool"?new Uint32Array(s.data.subarray(0,r)):t===this.n?this.fixed:null}assertNotDisposed(){if(this.state==="disposed")throw new Error("FruchtermanReingoldSimulation: disposed")}assertLoaded(){if(this.assertNotDisposed(),this.state!=="loaded")throw new Error("FruchtermanReingoldSimulation: not loaded")}}function pI(n,e,t,r){if(e!==null&&(!Number.isInteger(e)||e<1))throw ze(new Error("columns must be a positive integer"),"E_BAD_OPTION",{option:"columns",value:e});const o=new Float64Array(2*n);if(n===0)return o;const s=Math.min(e??Math.ceil(Math.sqrt(n)),n),i=Math.ceil(n/s),a=Math.max(s-1,i-1),c=a===0?0:2*t/a;for(let l=0;l<n;l++)o[2*l]=r[0]+(l%s-(s-1)/2)*c,o[2*l+1]=r[1]+(Math.floor(l/s)-(i-1)/2)*c;return o}function mI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(pI(t,e.columns??null,o,s),r,s),r,t)}function yI(n,e,t,r){if(e.length===0)return n.map(l=>-l);const o=n.slice(),s=new Array(e.length).fill(0),i=[];for(let l=0;l<e.length;l++){const u=e[l],d=t[l];i.push(1/d.reduce((f,h,g)=>f+h*u[g],0))}for(let l=e.length-1;l>=0;l--){const u=e[l];s[l]=i[l]*u.reduce((d,f,h)=>d+f*o[h],0);for(let d=0;d<o.length;d++)o[d]-=s[l]*t[l][d]}let a=1;if(e.length>0&&t.length>0){const l=t[t.length-1];a=e[e.length-1].reduce((d,f,h)=>d+f*l[h],0)/l.reduce((d,f)=>d+f*f,0)}const c=o.map(l=>a*l);for(let l=0;l<e.length;l++){const u=e[l],d=t[l],f=i[l]*d.reduce((h,g,w)=>h+g*c[w],0);for(let h=0;h<c.length;h++)c[h]+=u[h]*(s[l]-f)}return c.map(l=>-l)}function bI(n,e,t,r,o,s){const c=r.reduce((d,f,h)=>d+f*e[h],0);if(c>=0)return 0;let l=s;const u=20;for(let d=0;d<u;d++){const f=n.map((g,w)=>g+l*e[w]);if(o(f)<=t+1e-4*l*c)return l;l*=.5}return 0}function vI(n,e,t){const r=e.length,o=.001,s=n.map(h=>h.map(g=>g===0?0:1/g)),i=e.flat(),a=500,c=1e-5,l=10,u=[],d=[];for(let h=0;h<a;h++){const[g,w]=Xc(i,s,o,t),p=yI(w,u,d),m=bI(i,p,g,w,I=>Xc(I,s,o,t)[0],1);if(m===0){if(u.length===0)break;u.length=0,d.length=0;continue}const y=[...i];for(let I=0;I<i.length;I++)i[I]+=m*p[I];const[,b]=Xc(i,s,o,t),v=i.map((I,k)=>I-y[k]),A=b.map((I,k)=>I-w[k]);if(v.reduce((I,k,N)=>I+k*A[N],0)>1e-10&&(u.push(v),d.push(A)),u.length>l&&(u.shift(),d.shift()),Math.sqrt(b.reduce((I,k)=>I+k*k,0))<c)break}const f=[];for(let h=0;h<r;h++)f.push(i.slice(h*t,(h+1)*t));return f}function AI(n,e,t){const r=t.length;for(let o=0;o<r;o++)for(let s=o+1;s<r;s++){const i=e[o].map((u,d)=>u-e[s][d]),a=Math.sqrt(i.reduce((u,d)=>u+d*d,0)),c=t[o][s],l=a*c-1;n+=l*l}return n}function EI(n,e,t,r){const o=t.length;for(let s=0;s<o;s++)for(let i=s+1;i<o;i++){const a=e[s].map((f,h)=>f-e[i][h]),c=Math.sqrt(a.reduce((f,h)=>f+h*h,0))||1e-10,l=a.map(f=>f/c),u=t[s][i],d=c*u-1;for(let f=0;f<r;f++){const h=2*u*d*l[f];n[s*r+f]+=h,n[i*r+f]-=h}}}function Xc(n,e,t,r){const o=e.length,s=[];for(let l=0;l<o;l++)s.push(n.slice(l*r,(l+1)*r));let i=0;const a=new Array(r).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)a[u]+=s[l][u];i+=.5*t*a.reduce((l,u)=>l+u*u,0),i=AI(i,s,e);const c=new Array(n.length).fill(0);for(let l=0;l<o;l++)for(let u=0;u<r;u++)c[l*r+u]+=t*a[u];return EI(c,s,e,r),[i,c]}const _I=1e6,II=42,kI=24;function ow(n,e){const t=kI*n*n,r=e===null?`kamadaKawai: ${n} nodes need about ${t} bytes of n x n memory, more than this runtime could allocate. Pass a maxNodes to refuse such graphs up front.`:`kamadaKawai: ${n} nodes exceeds maxNodes ${e}; it would allocate about ${t} bytes. Pass a larger maxNodes to allow it.`;return Object.assign(new RangeError(r),{code:"E_TOO_LARGE",params:{nodeCount:n,maxNodes:e,bytes:t}})}function SI(n,e){let t=null;return e===!0?t=n.edges.byRole("weight"):typeof e=="string"&&(t=n.edges.get(e)),t?.dtype==="f64"&&t.meta.components===1?Va(n,t.data):Zg(e,n)}function PI(n,e){const t=n.nodeCount;let r;if(e.dist!==null&&e.dist!==void 0){if(e.dist.length!==t*t)throw ze(new RangeError(`kamadaKawai: dist has ${e.dist.length} values, expected ${t*t} (n * n)`),"E_BAD_OPTION",{option:"dist",length:e.dist.length,expected:t*t});if(t>=2&&!e.dist.some((o,s)=>Number.isFinite(o)&&s%(t+1)!==0))throw ze(new RangeError("kamadaKawai: dist has no finite distance between two different nodes; was it computed from a graph without edges?"),"E_BAD_OPTION",{option:"dist"});r=e.dist}else{const o=SI(n,e.weight??!0);let s;try{s=new Float64Array(t*t).fill(Number.POSITIVE_INFINITY)}catch(c){throw c instanceof RangeError?ow(t,null):c}const{rowPtr:i,colIdx:a}=n;for(let c=0;c<t;c++){s[c*t+c]=0;for(let l=i[c];l<i[c+1];l++){const u=o===null?1:o[l];if(!(u>=0))throw ze(new RangeError(`kamadaKawai: weights are distances and must be >= 0, got ${u}`),"E_BAD_WEIGHT",{weight:u});const d=c*t+a[l];u<s[d]&&(s[d]=u)}}for(let c=0;c<t;c++)for(let l=0;l<t;l++){const u=s[l*t+c];if(u!==Number.POSITIVE_INFINITY)for(let d=0;d<t;d++){const f=u+s[c*t+d];f<s[l*t+d]&&(s[l*t+d]=f)}}r=s}return Array.from({length:t},(o,s)=>Array.from({length:t},(i,a)=>{const c=r[s*t+a];return s===a?0:Number.isFinite(c)?c:_I}))}function xI(n,e,t){const r=n.nodeCount,{pos:o}=e;if(o!=null){if(o.length!==t*r)throw ze(new RangeError(`kamadaKawai: pos has ${o.length} values, expected ${t*r} (dim * nodeCount)`),"E_BAD_OPTION",{option:"pos",length:o.length,expected:t*r});return Array.from({length:r},(i,a)=>Array.from(o.subarray(t*a,t*a+t),c=>Number.isNaN(c)?0:c))}if(t===2){const i=ds.linspace(0,2*Math.PI,r+1);return Array.from({length:r},(a,c)=>[yn(i[c]),Jt(i[c])])}const s=new Float64Array(3*r).fill(Number.NaN);return bi(n,s,e.seed===void 0?II:e.seed,3,1,null,"fr"),Array.from({length:r},(i,a)=>Array.from(s.subarray(3*a,3*a+3)))}function CI(n,e={}){const t=co(n),r=qg(e.dim),o=t.nodeCount;if(e.maxNodes!==void 0&&(o>e.maxNodes||Number.isNaN(e.maxNodes)))throw ow(o,e.maxNodes);if(o<=1){const a=new Float32Array(r*o);return o===1&&a.set(Array.from({length:r},(c,l)=>e.center?.[l]??0)),{positions:a,dim:r,n:o}}const s=vI(PI(t,e),xI(t,e,r),r),i=Float64Array.from(s.flat());return Jn(i,r,e.scale??1,e.center),{positions:Float32Array.from(i),dim:r,n:o}}class NI{constructor(e){this.n=e,this.cw=Array.from({length:e},()=>new Map),this.ccw=Array.from({length:e},()=>new Map),this.first=new Int32Array(e).fill(-1)}has(e,t){return this.cw[e].has(t)}addCw(e,t,r){if(r<0){this.cw[e].set(t,t),this.ccw[e].set(t,t),this.first[e]=t;return}const o=this.cw[e].get(r);if(o===void 0)throw new Error("Cannot add edge. Reference neighbor does not exist");this.cw[e].set(r,t),this.cw[e].set(t,o),this.ccw[e].set(o,t),this.ccw[e].set(t,r)}addCcw(e,t,r){if(r<0){this.addCw(e,t,-1);return}this.addCw(e,t,this.ccw[e].get(r)??-1),r===this.first[e]&&(this.first[e]=t)}addFirst(e,t){this.addCcw(e,t,this.first[e])}nextFace(e,t){return[t,this.ccw[t].get(e)??-1]}neighboursCw(e){const t=this.first[e];if(t<0)return[];const r=[t];for(let o=this.cw[e].get(t)??t;o!==t;o=this.cw[e].get(o)??t)r.push(o);return r}}const _i=(n=-1,e=-1)=>({low:n,high:e}),Ln=n=>n.low<0&&n.high<0;class TI{constructor(e){this.adj=e,this.lowpt=new Map,this.lowpt2=new Map,this.nesting=new Map,this.oriented=new Set,this.ordered=[],this.ref=new Map,this.side=new Map,this.stack=[],this.stackBottom=new Map,this.lowptEdge=new Map,this.leftRef=new Map,this.rightRef=new Map,this.roots=[],this.n=e.length,this.height=new Int32Array(this.n).fill(-1),this.parentEdge=new Float64Array(this.n).fill(-1),this.out=Array.from({length:this.n},()=>[])}key(e,t){return e*this.n+t}target(e){return e%this.n}low(e){return this.lowpt.get(e)??0}run(){const{n:e}=this,t=this.adj.reduce((s,i)=>s+i.length,0)/2;if(e>2&&t>3*e-6)return null;for(let s=0;s<e;s++)this.height[s]<0&&(this.height[s]=0,this.roots.push(s),this.orient(s));const r=s=>[...this.out[s]].sort((i,a)=>(this.nesting.get(this.key(s,i))??0)-(this.nesting.get(this.key(s,a))??0));this.ordered=Array.from({length:e},(s,i)=>r(i));for(const s of this.roots)if(!this.test(s))return null;for(const s of this.oriented)this.nesting.set(s,this.sign(s)*(this.nesting.get(s)??0));const o=new NI(e);for(let s=0;s<e;s++){this.ordered[s]=r(s);let i=-1;for(const a of this.ordered[s])o.addCw(s,a,i),i=a}for(const s of this.roots)this.embed(s,o);return o}orient(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];for(;r[s]<this.adj[s].length;){const a=this.adj[s][r[s]],c=this.key(s,a),l=this.key(a,s);if(!o.has(c)){if(this.oriented.has(c)||this.oriented.has(l)){r[s]++;continue}if(this.oriented.add(c),this.out[s].push(a),this.lowpt.set(c,this.height[s]),this.lowpt2.set(c,this.height[s]),this.height[a]<0){this.parentEdge[a]=c,this.height[a]=this.height[s]+1,t.push(s,a),o.add(c);break}this.lowpt.set(c,this.height[a])}if(this.nesting.set(c,2*this.low(c)+((this.lowpt2.get(c)??0)<this.height[s]?1:0)),i>=0){const u=this.low(i),d=this.lowpt2.get(i)??0,f=this.low(c),h=this.lowpt2.get(c)??0;f<u?(this.lowpt2.set(i,Math.min(u,h)),this.lowpt.set(i,f)):f>u?this.lowpt2.set(i,Math.min(d,f)):this.lowpt2.set(i,Math.min(d,h))}r[s]++}}}conflicting(e,t){return!Ln(e)&&this.low(e.high)>this.low(t)}lowest(e){return Ln(e.left)?this.low(e.right.low):Ln(e.right)?this.low(e.left.low):Math.min(this.low(e.left.low),this.low(e.right.low))}top(){return this.stack.length===0?null:this.stack[this.stack.length-1]}test(e){const t=[e],r=new Int32Array(this.n),o=new Set;for(;t.length>0;){const s=t.pop()??0,i=this.parentEdge[s];let a=!1;const c=this.ordered[s];for(;r[s]<c.length;){const l=c[r[s]],u=this.key(s,l);if(!o.has(u)){if(this.stackBottom.set(u,this.top()),u===this.parentEdge[l]){t.push(s,l),o.add(u),a=!0;break}this.lowptEdge.set(u,u),this.stack.push({left:_i(),right:_i(u,u)})}if(this.low(u)<this.height[s]){if(l===c[0])this.lowptEdge.set(i,this.lowptEdge.get(u)??-1);else if(!this.addConstraints(u,i))return!1}r[s]++}!a&&i>=0&&this.removeBackEdges(i)}return!0}addConstraints(e,t){const r={left:_i(),right:_i()};for(;;){const o=this.stack.pop();if(Ln(o.left)||([o.left,o.right]=[o.right,o.left]),!Ln(o.left))return!1;if(this.low(o.right.low)>this.low(t)?(Ln(r.right)?r.right={...o.right}:this.ref.set(r.right.low,o.right.high),r.right.low=o.right.low):this.ref.set(o.right.low,this.lowptEdge.get(t)??-1),this.top()===(this.stackBottom.get(e)??null))break}for(let o=this.top();o!==null&&(this.conflicting(o.left,e)||this.conflicting(o.right,e));o=this.top()){const s=this.stack.pop();if(this.conflicting(s.right,e)&&([s.left,s.right]=[s.right,s.left]),this.conflicting(s.right,e))return!1;this.ref.set(r.right.low,s.right.high),s.right.low>=0&&(r.right.low=s.right.low),Ln(r.left)?r.left={...s.left}:this.ref.set(r.left.low,s.left.high),r.left.low=s.left.low}return Ln(r.left)&&Ln(r.right)||this.stack.push(r),!0}removeBackEdges(e){const t=Math.floor(e/this.n),r=o=>this.ref.get(o)??-1;for(;this.stack.length>0&&this.lowest(this.top())===this.height[t];){const o=this.stack.pop();o.left.low>=0&&this.side.set(o.left.low,-1)}if(this.stack.length>0){const o=this.stack.pop();for(;o.left.high>=0&&this.target(o.left.high)===t;)o.left.high=r(o.left.high);for(o.left.high<0&&o.left.low>=0&&(this.ref.set(o.left.low,o.right.low),this.side.set(o.left.low,-1),o.left.low=-1);o.right.high>=0&&this.target(o.right.high)===t;)o.right.high=r(o.right.high);o.right.high<0&&o.right.low>=0&&(this.ref.set(o.right.low,o.left.low),this.side.set(o.right.low,-1),o.right.low=-1),this.stack.push(o)}if(this.low(e)<this.height[t]){const o=this.top(),s=o.left.high,i=o.right.high;this.ref.set(e,s>=0&&(i<0||this.low(s)>this.low(i))?s:i)}}sign(e){const t=[e],r=new Map;for(;t.length>0;){const o=t.pop()??0,s=this.ref.get(o)??-1;if(s>=0)t.push(o,s),r.set(o,s),this.ref.set(o,-1);else{const i=r.get(o)??-1;this.side.set(o,(this.side.get(o)??1)*(i>=0?this.side.get(i)??1:1))}}return this.side.get(e)??1}embed(e,t){const r=[e],o=new Int32Array(this.n);for(;r.length>0;){const s=r.pop()??0,i=this.ordered[s];for(;o[s]<i.length;){const a=i[o[s]++],c=this.key(s,a);if(c===this.parentEdge[a]){t.addFirst(a,s),this.leftRef.set(s,a),this.rightRef.set(s,a),r.push(s,a);break}(this.side.get(c)??1)===1?t.addCw(a,s,this.rightRef.get(a)??-1):(t.addCcw(a,s,this.leftRef.get(a)??-1),this.leftRef.set(a,s))}}}}function OI(n,e,t,r){const{n:o}=n;if(r.has(e*o+t))return[];r.add(e*o+t);let s=e,i=t;const a=[e],c=new Set(a);let[,l]=n.nextFace(s,i);for(;i!==e||l!==t;)c.has(i)?(n.addCw(s,l,i),n.addCcw(l,s,i),r.add(i*o+l),r.add(l*o+s),i=s):(c.add(i),a.push(i)),s=i,[i,l]=n.nextFace(i,l),r.add(s*o+i);return a}function $I(n,e,t){let[,r]=n.nextFace(e,t),[,o]=n.nextFace(t,r);if(!(e===t||e===r))for(;e!==o;)n.has(e,r)?[e,t,r]=[t,r,o]:(n.addCw(e,r,t),n.addCcw(r,e,t),[t,r]=[r,o]),[,o]=n.nextFace(t,r)}function RI(n){const{n:e}=n,t=new Uint8Array(e),r=[];for(let a=0;a<e;a++)if(t[a]!==1){r.push(a),t[a]=1;for(const c=[a];c.length>0;)for(const l of n.neighboursCw(c.pop()??0))t[l]===0&&(t[l]=1,c.push(l))}for(let a=0;a+1<r.length;a++)n.addFirst(r[a],r[a+1]),n.addFirst(r[a+1],r[a]);let o=[];const s=[],i=new Set;for(let a=0;a<e;a++){const c=n.first[a];if(c<0)continue;let l=c;do{const u=OI(n,a,l,i);u.length>0&&(s.push(u),u.length>o.length&&(o=u)),l=n.cw[a].get(l)??c}while(l!==c)}for(const a of s)a!==o&&$I(n,a[0],a[1]);return o}class DI{constructor(e,t){this.embedding=e,this.ccwNbr=new Map,this.cwNbr=new Map;const{n:r}=e;this.v1=t[0],this.v2=t[1],this.chords=new Int32Array(r),this.marked=new Uint8Array(r),this.ready=new Set(t);let o=this.v2;for(let s=2;s<t.length;s++)this.ccwNbr.set(o,t[s]),o=t[s];this.ccwNbr.set(o,this.v1),o=this.v1;for(let s=t.length-1;s>0;s--)this.cwNbr.set(o,t[s]),o=t[s];for(const s of t)this.countChords(s,null)}run(){const{n:e}=this.embedding,t=new Array(e);t[0]=[this.v1,[]],t[1]=[this.v2,[]],this.ready.delete(this.v1),this.ready.delete(this.v2);for(let r=e-1;r>1;r--){const o=this.ready.values().next().value;this.ready.delete(o),this.marked[o]=1;const[s,i]=this.contourEnds(o),a=this.replaceContour(o,s,i);a.length===2?(this.releaseChord(s),this.releaseChord(i)):this.addInner(new Set(a.slice(1,-1))),t[r]=[o,a]}return t}isOuterNbr(e,t){return this.ccwNbr.get(e)===t||this.cwNbr.get(e)===t}isOnOuter(e){return this.marked[e]===0&&(this.ccwNbr.has(e)||e===this.v1)}countChords(e,t){for(const r of this.embedding.neighboursCw(e))this.isOnOuter(r)&&!this.isOuterNbr(e,r)&&(this.chords[e]++,this.ready.delete(e),t!==null&&!t.has(r)&&(this.chords[r]++,this.ready.delete(r)))}contourEnds(e){let t=-1,r=-1;for(const o of this.embedding.neighboursCw(e))if(this.isOnOuter(o)&&(o===this.v1?t=this.v1:o===this.v2?r=this.v2:this.cwNbr.get(o)===e?t=o:r=o),t>=0&&r>=0)break;return[t,r]}replaceContour(e,t,r){const o=[t];for(let s=t;s!==r;){const i=this.embedding.ccw[e].get(s)??r;o.push(i),this.cwNbr.set(s,i),this.ccwNbr.set(i,s),s=i}return o}releaseChord(e){--this.chords[e]===0&&this.ready.add(e)}addInner(e){for(const t of e)this.ready.add(t),this.countChords(t,e)}}function LI(n,e){return new DI(n,e).run()}function MI(n){const{n:e}=n,t=new Float64Array(2*e);if(e<4){const d=[0,0,2,0,1,1];return t.set(d.slice(0,2*e)),t}const r=LI(n,RI(n)),o=new Int32Array(e).fill(-1),s=new Int32Array(e).fill(-1),i=new Float64Array(e),a=new Float64Array(e),[c,l,u]=[r[0][0],r[1][0],r[2][0]];s[c]=u,i[l]=1,i[u]=1,a[u]=1,s[u]=l;for(let d=3;d<e;d++){const[f,h]=r[d],g=h[0],w=h[1],p=h[h.length-1],m=h[h.length-2],y=h.length>2;i[w]+=1,i[p]+=1;let b=0;for(let v=1;v<h.length;v++)b+=i[h[v]];i[f]=Math.floor((-a[g]+b+a[p])/2),a[f]=Math.floor((a[g]+b+a[p])/2),i[p]=b-i[f],y&&(i[w]-=i[f]),s[g]=f,s[f]=p,y?(o[f]=w,s[m]=-1):o[f]=-1}t[2*c+1]=a[c];for(const d=[c];d.length>0;){const f=d.pop()??0;for(const h of[o[f],s[f]])h>=0&&(t[2*h]=t[2*f]+i[h],t[2*h+1]=a[h],d.push(h))}return t}function UI(n){const e=[];for(let t=0;t<n.nodeCount;t++){const r=[];for(let o=n.rowPtr[t];o<n.rowPtr[t+1];o++){const s=n.colIdx[o];s!==t&&s!==r[r.length-1]&&r.push(s)}e.push(r)}return e}function FI(n,e,t){const r=new TI(UI(n)).run();if(r===null)throw Object.assign(new Error("G is not planar."),{code:"E_NOT_PLANAR",params:{nodeCount:n.nodeCount,edgeCount:n.edgeCount}});return Jn(MI(r),2,e,t)}function BI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(Rn(FI(co(n),o,s),r,s),r,t)}function sw(n,e,t,r,o=0){const s=new Float64Array(2*n).fill(Number.NaN);if(e.length===0)return s;const i=o==="networkx"?Math.PI/e.length:o;if(!Number.isFinite(i))throw ze(new TypeError(`rotate must be a finite number of radians or "networkx", not ${String(o)}`),"E_BAD_OPTION",{option:"rotate",value:o});const a=t/e.length;let c=a;return e[0].length===1&&(s[2*e[0][0]]=r[0],s[2*e[0][0]+1]=r[1]),e.forEach((l,u)=>{if(l.length===0||u===0&&l.length===1)return;const d=ds.linspace(0,2*Math.PI,l.length+1),f=(u+1)*i;for(let h=0;h<l.length;h++)s[2*l[h]]=yn(d[h]+f)*c+r[0],s[2*l[h]+1]=Jt(d[h]+f)*c+r[1];c+=a}),s}function zI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),{nlist:i}=e,a=typeof i=="string"?Kg(n,i,"nlist"):i?.map(c=>ss(n,c))??[Array.from({length:t},(c,l)=>l)];for(const c of a)for(let l=0;l<c.length;l++)if(!Number.isInteger(c[l])||c[l]<0||c[l]>=t)throw ze(new Error(`shell node index ${String(c[l])} is not a node of the graph`),"E_BAD_NODE",{option:"nlist",index:c[l]});return Wt(Rn(sw(t,a,o,s,e.rotate),r,s),r,t)}function GI(n,e){const t=new Map;for(let r=n.rowPtr[e];r<n.rowPtr[e+1];r++)t.has(n.colIdx[r])||t.set(n.colIdx[r],n.arcToEdge[r]);return[...t.keys()].sort((r,o)=>(t.get(r)??0)-(t.get(o)??0))}function WI(n,e){const t=n.nodeCount,r=new Int32Array(t).fill(-1);if(t===0)return{rings:[],parent:r};if(e===null){let a=0,c=-1;for(let l=0;l<t;l++){let u=0;for(let d=n.rowPtr[l];d<n.rowPtr[l+1];d++)(d===n.rowPtr[l]||n.colIdx[d]!==n.colIdx[d-1])&&u++;u>c&&(a=l,c=u)}e=a}else if(!Number.isInteger(e)||e<0||e>=t)throw ze(new Error(`root node ${String(e)} is not in the graph`),"E_BAD_NODE",{option:"root",index:e});const o=new Uint8Array(t);o[e]=1;const s=[[e]];for(let a=s[0];a.length>0;){const c=[];for(const l of a)for(const u of GI(n,l))o[u]===0&&(o[u]=1,r[u]=l,c.push(u));c.length>0&&s.push(c),a=c}const i=[];for(let a=0;a<t;a++)o[a]===0&&i.push(a);return i.length>0&&s.push(i),{rings:s,parent:r}}function VI(n,e,t,r){const o=new Float64Array(n);for(let s=r-1;s>=0;s--)for(const i of e[s])o[i]||=1,s>0&&(o[t[i]]+=o[i]);return o}function jI(n,e,t,r,o){const s=new Float64Array(2*n);if(n===0)return s;const i=e.length>1?r/(e.length-1):0,a=e.at(-1)??[],c=e.length>1&&t[a[0]]===-1?e.length-1:e.length,l=VI(n,e,t,c),u=new Float64Array(n),d=new Float64Array(n),f=new Float64Array(n);d[e[0][0]]=2*Math.PI,c>1&&e[1].length===1&&(u[e[0][0]]=Math.PI/4-Math.PI);const h=(g,w,p)=>{s[2*g]=yn(p)*w+o[0],s[2*g+1]=Jt(p)*w+o[1]};h(e[0][0],0,0);for(let g=1;g<c;g++){const w=2*Of(g/(g+1));for(const p of e[g]){const m=t[p],y=d[m]*l[p]/l[m],b=u[m]+f[m]+y/2;f[m]+=y,h(p,g*i,b),d[p]=Math.min(y,w),u[p]=b-d[p]/2}}return c<e.length&&a.forEach((g,w)=>{h(g,r,2*Math.PI*w/a.length)}),s}function qI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=e.root??null,{arrangement:a="rings",rotate:c}=e;if(a!=="rings"&&a!=="sectors")throw ze(new Error(`arrangement must be "rings" or "sectors", not ${String(a)}`),"E_BAD_OPTION",{option:"arrangement",value:a});if(a==="sectors"&&c!==void 0&&c!==0)throw ze(new Error('rotate turns each ring separately, which only arrangement: "rings" allows'),"E_BAD_OPTION",{option:"rotate",value:c});const{rings:l,parent:u}=WI(co(n),i===null?null:xe(n,i));if(a==="sectors")return Wt(Rn(jI(t,l,u,o,s),r,s),r,t);const d=l.length>1?l.length/(l.length-1):1;return Wt(Rn(sw(t,l,o*d,s,c),r,s),r,t)}class iw{constructor(e){this.seed=e??Math.floor(Math.random()*1e6),this.m=34359738337,this.a=185852,this.c=1,this._state=this.seed%this.m}_next(){return this._state=(this.a*this._state+this.c)%this.m,this._state/this.m}rand(e=null){if(e===null)return this._next();if(typeof e=="number"){const r=[];for(let o=0;o<e;o++)r.push(this._next());return r}if(e.length===1){const r=[];for(let o=0;o<e[0];o++)r.push(this._next());return r}const t=[];for(let r=0;r<e[0];r++)t.push(this.rand(e.slice(1)));return t}}function HI(n,e,t,r,o){const s=new iw(o??void 0),i=new Float64Array(n*e);for(let a=0;a<n*e;a++)i[a]=s.rand()*t+r[a%e];return i}function KI(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(HI(t,r,o,s,e.seed??null),r,t)}const YI=1e-9,XI=5e3;function QI(n,e,t,r,o){const s=n.nodeCount,i=new Float64Array(s*e);if(s<=2){for(let w=0;w<s;w++){const p=w===0?-t:t;for(let m=0;m<e;m++)i[e*w+m]=s===1?r[m]:r[m]+p}return i}const{rowPtr:a,colIdx:c}=n,l=(w,p)=>c[p]!==w&&(p===a[w]||c[p]!==c[p-1]),u=new Float64Array(s);for(let w=0;w<s;w++)for(let p=a[w];p<a[w+1];p++)u[w]+=l(w,p)?1:0;const d=w=>{const p=new Float64Array(s);for(let m=0;m<s;m++){let y=u[m]*w[m];for(let b=a[m];b<a[m+1];b++)l(m,b)&&(y-=w[c[b]]);p[m]=y}return p},f=YI*2*Math.max(1,...u),h=new iw(o??void 0),g=[new Float64Array(s).fill(1/Math.sqrt(s))];for(let w=0;w<e;w++){const p=Float64Array.from({length:s},()=>h.rand()-.5),m=aw(p,g)?JI(d,p,g,f):p.fill(0);g.push(m);for(let y=0;y<s;y++)i[e*y+w]=m[y]}Jn(i,e,t);for(let w=0;w<s*e;w++)i[w]+=r[w%e];return i}function JI(n,e,t,r){let o=n(e),s=null;for(let i=0;i<XI;i++){const a=Qc(e,o),c=o.map((p,m)=>p-a*e[m]);if(Jc(c)<r)break;const l=[e];for(const p of s===null?[c]:[c,s])aw(p,[...t,...l])&&l.push(p);const u=[o,...l.slice(1).map(n)],d=l.map(p=>u.map(m=>Qc(p,m))),f=ZI(d),h=new Float64Array(e.length),g=new Float64Array(e.length),w=new Float64Array(e.length);l.forEach((p,m)=>{for(let y=0;y<e.length;y++)h[y]+=f[m]*p[y],g[y]+=f[m]*u[m][y],m>0&&(w[y]+=f[m]*p[y])}),e.set(h),o=g,s=w}return e}function ZI(n){const e=n.length,t=n.map((o,s)=>n.map((i,a)=>s===a?1:0));for(let o=0;o<50;o++)for(let s=0;s<e;s++)for(let i=s+1;i<e;i++)ek(n,t,s,i);let r=0;for(let o=1;o<e;o++)n[o][o]<n[r][r]&&(r=o);return t.map(o=>o[r])}function ek(n,e,t,r){if(Math.abs(n[t][r])<1e-300)return;const o=(n[r][r]-n[t][t])/(2*n[t][r]),s=Math.sign(o||1)/(Math.abs(o)+Math.sqrt(o*o+1)),i=1/Math.sqrt(s*s+1),a=s*i;for(const c of[n,e])for(const l of c)[l[t],l[r]]=[i*l[t]-a*l[r],a*l[t]+i*l[r]];[n[t],n[r]]=[n[t].map((c,l)=>i*c-a*n[r][l]),n[t].map((c,l)=>a*c+i*n[r][l])]}function aw(n,e){const t=Jc(n);for(let o=0;o<2;o++)for(const s of e){const i=Qc(n,s);for(let a=0;a<n.length;a++)n[a]-=i*s[a]}const r=Jc(n);if(r<=1e-8*t)return!1;for(let o=0;o<n.length;o++)n[o]/=r;return!0}function Qc(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function Jc(n){let e=0;for(const t of n)e+=t*t;return Math.sqrt(e)}function tk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e);return Wt(QI(co(n),r,o,s,e.seed??null),r,t)}function nk(n,e,t,r,o){const s=new Float64Array(2*n);if(o){let c=r;c+=1/(.5*c);for(let l=0;l<n;l++){const u=.5*c;c+=1/u,s[2*l]=yn(c)*u,s[2*l+1]=Jt(c)*u}}else for(let i=0;i<n;i++)s[2*i]=yn(r*i)*i,s[2*i+1]=Jt(r*i)*i;return Jn(s,2,e,t)}function rk(n,e={}){const{n:t,dim:r,scale:o,center:s}=en(n,e),i=nk(t,o,s,e.resolution??.35,e.equidistant??!1);return Wt(Rn(i,r,s),r,t)}function ok(n,e,t){switch(n){case"forceatlas2":return t?.forceAtlas2!==void 0?t.forceAtlas2(e):new uI(e);case"fruchtermanReingold":case"spring":return t?.fruchtermanReingold!==void 0?t.fruchtermanReingold(e):new wI(e);case"spring-electrical":if(t?.springElectrical===void 0)throw new Error('createSimulation: "spring-electrical" has no CPU simulation; inject an accelerator that implements springElectrical');return t.springElectrical(e);default:{const r=n;throw new Error(`createSimulation: unknown simulation type ${String(r)}`)}}}const sk={animate:!1,animationDuration:500,fit:!0,padding:30,randomize:!0,refresh:1};function ik(n,e){const t=new Map;return n.nodes.forEach((o,s)=>{const i=o.data(e);if(typeof i=="number"||typeof i=="string"){const a=t.get(i);a===void 0?t.set(i,[s]):a.push(s)}}),[...t.keys()].sort((o,s)=>typeof o=="number"&&typeof s=="number"?o-s:String(o).localeCompare(String(s))).map(o=>t.get(o)??[])}const cw={random:(n,e)=>KI(n,e),circular:(n,e)=>eI(n,e),spiral:(n,e)=>rk(n,e),grid:(n,e)=>mI(n,e),spectral:(n,e)=>tk(n,e),planar:(n,e)=>BI(n,e),arf:(n,e)=>H_(n,e),"kamada-kawai":(n,e)=>CI(n,e),shell:(n,e,t)=>{const r=e.nlist;return zI(n,{...e,nlist:r?.map(o=>Gt(t,o))})},multipartite:(n,e,t)=>{const r=e.subsets??"subset",o=typeof r=="string"?ik(t,r):r.map(s=>Gt(t,s));return K_(n,{...e,subsets:o})},bipartite:(n,e,t)=>{if(e.top===void 0)return Yg(n,e);const r=At(n.nodeCount);for(const o of Gt(t,e.top))pn(r,o,!0);return Yg(n,{...e,top:r})},bfs:(n,{root:e,...t},r)=>X_(n,{...t,start:ao(r,e,"graphty layout: root")}),radial:(n,e,t)=>qI(n,{...e,root:ao(t,e.root,"graphty layout: root")})},ak={forceatlas2:{maxIter:100},fruchtermanReingold:{iterations:50}},lw={forceatlas2:"forceatlas2","fruchterman-reingold":"fruchtermanReingold","spring-electrical":"spring-electrical"},ck=[...Object.keys(cw),...Object.keys(lw)];function uw(n,e){if(n===void 0){const t=r=>Number.isFinite(r)?r:1;return{x1:0,y1:0,w:t(e.width()),h:t(e.height())}}return"w"in n?n:{x1:n.x1,y1:n.y1,w:n.x2-n.x1,h:n.y2-n.y1}}function Zc(n){return{radius:Math.max(Math.min(n.w,n.h)/2,1),center:[n.x1+n.w/2,n.y1+n.h/2,0]}}function dw(n,e,t,r){const o=new Float64Array(2*t);for(let a=0;a<t;a++)o[2*a]=n[e*a],o[2*a+1]=n[e*a+1];const{radius:s,center:i}=Zc(r);return Jn(o,2,s,i)}function lk(n,e,t,r){let o=0,s=0,i=0;for(let f=0;f<t;f++)_e(e,f)&&(o+=n[3*f],s+=n[3*f+1],i++);o/=i,s/=i;const a=o>=r.x1&&o<=r.x1+r.w&&s>=r.y1&&s<=r.y1+r.h,c=(f,h,g,w)=>h===0?1/0:((h>0?w:g)-f)/h;let l=1/0,u=0;for(let f=0;f<t;f++)if(!_e(e,f)){const h=n[3*f]-o,g=n[3*f+1]-s;l=Math.min(l,c(o,h,r.x1,r.x1+r.w),c(s,g,r.y1,r.y1+r.h)),u=Math.max(u,Math.hypot(h,g))}a?Number.isFinite(l)||(l=1):l=u>0?Zc(r).radius/u:1;const d=new Float64Array(2*t);for(let f=0;f<t;f++){const h=_e(e,f)?1:l;d[2*f]=o+h*(n[3*f]-o),d[2*f+1]=s+h*(n[3*f+1]-s)}return d}function uk(n,e){const t={};for(const r of["nodeMass","nodeSize"]){const o=e[r];if(Array.isArray(o)||ArrayBuffer.isView(o)&&!(o instanceof Float32Array))t[r]=Float32Array.from(o);else if(typeof o=="string"){const s={};n.nodes.forEach(i=>{const a=i.data(o);typeof a=="number"&&Number.isFinite(a)&&(s[i.id()]=a)}),t[r]=s}}return t}function fw(n){return(e,t)=>Number.isNaN(n[2*t])?e.position():{x:n[2*t],y:n[2*t+1]}}function hw(n,e,t){const r=fw(t);e.layoutPositions(n,n.options,r)}function gw(n){return{...n,dim:n.dim??2,scale:1,center:void 0,seed:n.seed??null,weight:n.weight!==void 0}}function ww(n){return hi(n.eles.not(":parent"),{weight:n.weight})}function pw(n,e){if((e?n.animate!==!0&&!!n.animate:!!n.animate)&&!n.cy.styleEnabled())throw new Error(`${n.name}: animate needs a core that renders; create a headless core with styleEnabled: true, or pass animate: false`)}function dk(n,e){const t=n.options;pw(t,!1);const r=ww(t),o=e(r.snapshot,gw(t),r);hw(n,r.nodes,dw(o.positions,o.dim,o.n,uw(t.boundingBox,t.cy)))}function mw(n,e){for(;!n.settled&&!e.stopped&&!e.options.cy.destroyed();){const t=n.step(50);if(t instanceof Promise)return t.then(()=>mw(n,e))}}function fk(n,e){const t=n.options;if(pw(t,!0),$c(t.name,t.gpu),n.stopped=!1,t.accelerator!==void 0){n.backend=t.accelerator===null?{ran:"cpu",reason:"accelerator: null was passed",device:null}:{ran:"gpu",reason:null,device:t.accelerator.kind},tl(n,e,t.accelerator);return}const r=t.gpu==="require"?null:xg(t.gpu);if(r!==null){n.backend=Lc(r,!1,""),Dc(r,t.eles.nodes().length),tl(n,e,null);return}n.looping=!0,Cg(t.cy,t.gpu).then(o=>{if(n.looping=!1,n.backend=Lc(o,o.gpu!==null,""),Dc(o,t.eles.nodes().length),n.stopped||t.cy.destroyed()){n.emit({type:"layoutstop",layout:n});return}tl(n,e,o.gpu?.accelerator??null)}).catch(o=>{n.looping=!1,t.cy.destroyed()||n.emit("layouterror",[o]),n.emit({type:"layoutstop",layout:n})})}const el=new WeakMap;function yw(n,e){let t=0,r=0;for(let o=0;o<e;o++)t+=n[3*o],r+=n[3*o+1];return e===0?[0,0,0]:[t/e,r/e,0]}function tl(n,e,t){const r=n.options;if(t===null&&e==="spring-electrical"){const O=n.backend?.reason??"none was available";n.backend=void 0;const T=new Error(`graphty-spring-electrical has no CPU simulation and runs only on the GPU; no GPU ran because ${O}`);bw(n,T);return}const o=ww(r),s=o.snapshot,i=s.nodeCount,a=uw(r.boundingBox,r.cy),{radius:c,center:l}=Zc(a),u=r.dim??2,d=new Float32Array(3*i),f=At(i),h=new Vg(r.seed??null);let g=!1;o.nodes.forEach((O,T)=>{const $=O.locked();g||=$,pn(f,T,$);const L=O.position(),F=$||r.randomize===!1;d[3*T]=F?L.x:a.x1+h.next()*a.w,d[3*T+1]=F?L.y:a.y1+h.next()*a.h,d[3*T+2]=F||u===2?0:(h.next()*2-1)*c});const w=r.randomize===!1&&!g?el.get(r.cy)?.get(e):void 0,p=w??c,m=ok(e,{...ak[e],...gw(r),...uk(o,r),scale:p,center:w===void 0?l:yw(d,i),iterationsPerStep:1},t);m.load(s,d),g&&m.setFixed(f);const y=bg(s),b=()=>{if(m.dispose(),y(),!g){const[O,T]=yw(d,i);let $=0;for(let L=0;L<i;L++)$=Math.max($,Math.hypot(d[3*L]-O,d[3*L+1]-T));if($>0){const L=el.get(r.cy)??new Map;L.set(e,p*c/$),el.set(r.cy,L)}}},v=()=>g?lk(d,f,i,a):dw(d,3,i,a),A=O=>{n.looping=!1,b(),r.cy.destroyed()||n.emit("layouterror",[O]),n.emit({type:"layoutstop",layout:n})};if(r.animate!==!0){const O=()=>{n.looping=!1,b(),r.cy.destroyed()?n.emit({type:"layoutstop",layout:n}):hw(n,o.nodes,v())},T=mw(m,n);T===void 0?O():(n.looping=!0,T.then(O,A));return}n.looping=!0,n.emit({type:"layoutstart",layout:n});let E=!0;const I=typeof requestAnimationFrame=="function"?requestAnimationFrame:O=>setTimeout(O,16),k=()=>{n.looping=!1,b(),r.stop!==void 0&&n.one("layoutstop",r.stop),n.emit({type:"layoutstop",layout:n})},N=()=>{if(r.cy.destroyed()){k();return}o.nodes.positions(fw(v())),r.fit!==!1&&r.cy.fit(r.eles,r.padding),E&&(E=!1,r.ready!==void 0&&n.one("layoutready",r.ready),n.emit({type:"layoutready",layout:n})),m.settled||n.stopped?k():I(C)},C=()=>{if(n.stopped||r.cy.destroyed()){N();return}let O;try{O=m.step(r.refresh??1)}catch(T){A(T);return}O instanceof Promise?O.then(N,A):N()};C()}function bw(n,e){n.looping=!0,Promise.resolve().then(()=>{n.looping=!1,n.emit("layouterror",[e]),n.emit({type:"layoutstop",layout:n})})}const vw=new WeakMap;function hk(){return this.options.cy.destroyed()?bw(this,cs()):vw.get(this)?.(this),this}function gk(){return this.looping?this.stopped=!0:this.emit({type:"layoutstop",layout:this}),this}function Aw(n,e){function t(o){this.options={...sk,...o},this.stopped=!1,this.looping=!1,vw.set(this,n)}const r={run:hk};return e&&(r.stop=gk),Object.assign(t.prototype,r),t}function wk(n){for(const[e,t]of Object.entries(cw))n("layout",`graphty-${e}`,Aw(r=>{dk(r,t)},!1));for(const[e,t]of Object.entries(lw))n("layout",`graphty-${e}`,Aw(r=>{fk(r,t)},!0))}const Ew=Symbol.for("@graphty/cytoscape-extensions");function pk(n){const e=n;e[Ew]!==!0&&(e[Ew]=!0,wk(n),R_(n),U_(n))}const _w=Object.assign(pk,{ALGORITHM_NAMES:T_,ASYNC_ALGORITHM_NAMES:O_,configureWebGpu:b_,GPU_SIZE_FLOOR:Ag,LAYOUT_NAMES:ck,toSnapshot:hi,writeData:io}),{cytoscape:Iw}=globalThis;typeof Iw=="function"&&Iw.use(_w);const nl=256,lo=65535,rl=lo*nl,Ve=4294967295,Ii=256,uo=64,ki=256,Vt=256,kw=32768,mk=3,yk=256,Sw=16*1024*1024,bk=4,vk=4*1024,Ak=64*1024*1024,Pw=16*1024*1024,xw=2,Rt=256,fo=32,jt=256,Cw=64,Cr=Object.freeze({maxIter:100,jitterTolerance:1,scalingRatio:2,gravity:1,strongGravity:!1,distributedAction:!1,linlog:!1,dissuadeHubs:!1,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),nr=Object.freeze({repulsion:"auto",exactMaxNodes:kw,nearMax:64,deterministic:!0,gridMax2D:512,gridMax3D:128,extentFactor:6,compat:"paper"}),Ek=.01,_k=1e-4,Ik=1e-8,Nw=128,ol=1,Tw=2,Si=.1,kk=.7,Sk=.9,Pk=5,xk=1e4,Ck=Object.freeze({k:null,iterations:50,fixed:null,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2,cooling:"linear"}),Nk=300,sl=Object.freeze({springLength:10,springCoefficient:.8,gravity:-12,dragCoefficient:.9,timeStep:.5,dim:2,scale:1,settleThreshold:.001,settleWindow:10,iterationsPerStep:1,maxInFlight:2}),Ow=Object.freeze({springElectrical:.003,fruchtermanReingold:.002}),Tk=2e3,Ok=2**128-2**104,$w=8,Rw=4,Dw=1024,Lw=1e-6,Mw=1.01,$k=24,$e=32,Rk=4096,Dk=2,Lk=24,Mk=32,ho=2139095040,Uk=.25,Fk=256,Bk=2,zk=100,Gk=256,Pi=64,il=32,Wk=4096,Uw=8,Nr=4,Vk=2147483648,jk=32,al=128,cl=65e3,Fw=2,qk=32,Hk=Object.freeze({});class S extends Error{constructor(e,t,r){super(t),this.name="WebGpuGraphError",this.code=e,this.details=r===void 0?Hk:Object.freeze({...r})}}function go(n){if(typeof n!="object"||n===null)return!1;const e=n;return e.name==="WebGpuGraphError"&&typeof e.code=="string"}function xi(n,e){return go(n)&&n.code===e}const Bw=Object.freeze(["maxBufferSize","maxStorageBufferBindingSize","maxStorageBuffersPerShaderStage","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX"]),Kk=["maxTextureDimension1D","maxTextureDimension2D","maxTextureDimension3D","maxTextureArrayLayers","maxBindGroups","maxBindGroupsPlusVertexBuffers","maxBindingsPerBindGroup","maxDynamicUniformBuffersPerPipelineLayout","maxDynamicStorageBuffersPerPipelineLayout","maxSampledTexturesPerShaderStage","maxSamplersPerShaderStage","maxStorageBuffersPerShaderStage","maxStorageBuffersInVertexStage","maxStorageBuffersInFragmentStage","maxStorageTexturesPerShaderStage","maxStorageTexturesInVertexStage","maxStorageTexturesInFragmentStage","maxUniformBuffersPerShaderStage","maxUniformBufferBindingSize","maxStorageBufferBindingSize","minUniformBufferOffsetAlignment","minStorageBufferOffsetAlignment","maxVertexBuffers","maxBufferSize","maxVertexAttributes","maxVertexBufferArrayStride","maxInterStageShaderVariables","maxColorAttachments","maxColorAttachmentBytesPerSample","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeWorkgroupsPerDimension","maxImmediateSize"],zw=new WeakSet;function Gw(n){return n instanceof Error?n.message:String(n)}function Ww(n){return n.architecture==="software"||n.architecture==="swiftshader"||n.architecture==="warp"||n.isFallbackAdapter===!0}function wo(n){const{info:e}=n,t=n.limits,r={};for(const o of Kk){const s=t[o];typeof s=="number"&&(r[o]=s)}return Object.freeze({vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description,software:Ww(e),subgroupMinSize:e.subgroupMinSize??0,subgroupMaxSize:e.subgroupMaxSize??0,features:Object.freeze(Array.from(n.features).sort()),limits:Object.freeze(r)})}async function Vw(n,e){let t;try{t=await n.requestAdapter({powerPreference:e})}catch(r){const o=`requestAdapter() threw: ${Gw(r)}`;throw new S("E_NO_ADAPTER",o,{reason:o})}if(t===null){const r="requestAdapter() returned null: no usable WebGPU adapter";throw new S("E_NO_ADAPTER",r,{reason:r})}return t}function Yk(n,e){const t={};if(e==="default")return t;if(e==="raise"){for(const r of Bw)t[r]=n.limits[r];return t}for(const r of Bw){const o=e[r];if(o===void 0)continue;const s=n.limits[r];if(o>s)throw new S("E_NO_DEVICE",`requested ${r} = ${o} exceeds the adapter's ${s}`,{reason:"limit",adapter:wo(n),limit:r,requested:o,available:s});t[r]=o}return t}function Xk(n,e,t){const r=[];for(const o of e){if(!n.features.has(o))throw new S("E_NO_DEVICE",`required feature "${o}" is not supported by the adapter`,{reason:"feature",adapter:wo(n),requested:o});r.includes(o)||r.push(o)}for(const o of t)n.features.has(o)&&!r.includes(o)&&r.push(o);return r}function jw(n,e){return new S("E_NO_DEVICE",`the adapter already created a device (an adapter is consumed by one requestDevice, spec 2.2 step 1): ${e}`,{reason:"consumed",adapter:wo(n)})}async function Qk(n,e){if(zw.has(n))throw jw(n,"recorded by this package");let t;try{t=await n.requestDevice(e)}catch(r){const o=Gw(r);throw/consumed|already been used/i.test(o)?jw(n,o):new S("E_NO_DEVICE",`requestDevice() rejected: ${o}`,{reason:"requestDevice",adapter:wo(n)})}return zw.add(n),t}function Jk(n,e,t,r){const o=new Set(n.features),s=o.has("subgroups");return{limits:n.limits,features:o,wgslFeatures:new Set(r),subgroupMinSize:s?e.subgroupMinSize??0:0,subgroupMaxSize:s?e.subgroupMaxSize??0:0,software:Ww(e),runtime:t,vendor:e.vendor,architecture:e.architecture,device:e.device,description:e.description}}function qw(n,e){const t=new Set(n.features),r=t.has("subgroups");return{limits:n.limits,features:t,wgslFeatures:e?.wgslFeatures??new Set,subgroupMinSize:r?e?.subgroupMinSize??0:0,subgroupMaxSize:r?e?.subgroupMaxSize??0:0,software:e?.software??!1,runtime:e?.runtime??"unknown",vendor:e?.vendor??"",architecture:e?.architecture??"",device:e?.device??"",description:e?.description??""}}function ll(n){const e=Math.min(nl,n.limits.maxComputeInvocationsPerWorkgroup);let t=1;for(;t*2<=e;)t*=2;return t}function ul(n){const e=n.limits.maxComputeWorkgroupsPerDimension;if(e!==lo)throw new S("E_NO_DEVICE",`maxComputeWorkgroupsPerDimension is ${e}; the dispatch planner and the WGSL prelude bake ${lo}`,{reason:"maxComputeWorkgroupsPerDimension",adapter:null,requested:lo,available:e});const t=ll(n);if(t<64)throw new S("E_NO_DEVICE",`the device allows a workgroup of ${t} invocations; the kernels need a power of two >= 64`,{reason:"limit",adapter:null,limit:"maxComputeInvocationsPerWorkgroup",requested:64,available:t})}function Zk(n,e){return n.messages.map(t=>{if(t.lineNum===0)return`${t.type} ${t.message}`;const r=t.lineNum-e;return r>=1?`${t.type} ${r}:${t.linePos} ${t.message}`:`${t.type} prelude:${t.lineNum}:${t.linePos} ${t.message}`})}class eS{constructor(e,t){this.live=new Map,this.residentBytes=0,this.pending=[],this.failure=null,this.serial=0,this.device=e,this.threshold=t??Sw}createBuffer(e){this.serial+=1;const t=e.label===void 0||e.label===""?`buffer-${this.serial}`:e.label,{size:r}=e,o=r>=this.threshold;o&&this.device.pushErrorScope("out-of-memory");const s=this.device.createBuffer({...e,label:t});if(this.live.set(s,r),this.residentBytes+=r,o){const i=this.device.popErrorScope().then(a=>{a!==null&&(this.live.has(s)&&(this.live.delete(s),this.residentBytes-=r),this.failure===null&&(this.failure=new S("E_OUT_OF_MEMORY",`out of memory creating "${t}" (${r} bytes, ${this.residentBytes} resident): ${a.message}`,{requested:r,resident:this.residentBytes,label:t})))},()=>{});this.pending.push(i)}return s}destroy(e){const t=this.live.get(e);t!==void 0&&(this.live.delete(e),this.residentBytes-=t),e.destroy()}async check(){for(;this.pending.length>0;){const e=this.pending.splice(0);await Promise.all(e)}if(this.failure!==null)throw this.failure}reset(){this.failure=null}get resident(){return this.residentBytes}get liveBuffers(){return this.live.size}}class tS{constructor(){this.queue=[]}set(e){this.queue.push(e)}take(){if(this.queue.length===0)return null;const e=this.queue.splice(0);let t=null;for(let r=e.length-1;r>=0;r-=1){const o=e[r];t=t===null?o:new S(o.code,o.message,{...o.details,next:t})}return t}get pending(){return this.queue.length>0}}function nS(n,e){const{message:t}=n;return n.constructor.name==="GPUOutOfMemoryError"?new S("E_OUT_OF_MEMORY",`uncaptured out-of-memory error on "${e}": ${t}`,{requested:0,resident:0,label:e}):new S("E_VALIDATION",`uncaptured validation error on "${e}": ${t}`,{label:e,message:t})}function rS(n,e,t){let r=!0;const o=n.label??"",s=i=>{if(!r)return;const a=nS(i.error,o);t!==null?t(a):e.set(a)};return n.addEventListener("uncapturederror",s),()=>{r=!1,typeof n.removeEventListener=="function"&&n.removeEventListener("uncapturederror",s)}}function oS(n,e){let t=!1;return n.lost.then(r=>(t||(t=!0,e(r)),r))}function Hw(n){return new S("E_DEVICE_LOST",`device lost (${n.reason}): ${n.message}`,{reason:n.reason,message:n.message})}const dl=16,sS=32,Kw=new WeakMap;let Yw=1;function iS(n){let e=Kw.get(n);return e===void 0&&(e=Yw,Yw+=1,Kw.set(n,e)),e}function aS(n,e){return n.offset<e.offset+e.size&&e.offset<n.offset+n.size}class cS{constructor(e,t,r,o,s){this.cache=new Map,this.device=e,this.spec=t,this.pipeline=o,this.layouts=s,this.workgroupSize=r.overrides.WG,this.entryPoint=r.entryPoint;const i=s.map(()=>[]);for(const a of t.bindings)i[a.group].push(a);for(const a of i)a.sort((c,l)=>c.binding-l.binding);this.groups=i,this.dynamicCounts=i.map(a=>a.filter(c=>c.kind==="uniform").length)}bind(e){const{id:t}=this.spec,r=new Map(this.spec.bindings.map(d=>[d.name,d]));for(const d of Object.keys(e))if(!r.has(d))throw new S("E_INVALID_ARGUMENT",`${t}: no binding named "${d}"`,{argument:"bindings",value:d,expected:[...r.keys()].join(", ")});const o=[];for(const d of this.spec.bindings){const f=e[d.name];if(f===void 0)throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" is missing`,{argument:"bindings",value:d.name,expected:"a Binding for every declared name"});if(!(Number.isInteger(f.size)&&f.size>0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has size ${f.size}`,{argument:d.name,value:f.size,expected:"size > 0 (a zero-length buffer is never bound)"});if(!(Number.isInteger(f.offset)&&f.offset>=0&&f.offset%ki===0))throw new S("E_INVALID_ARGUMENT",`${t}: binding "${d.name}" has offset ${f.offset}`,{argument:d.name,value:f.offset,expected:`a multiple of ${ki} (spec 2.6: the offset alignment the package always honours)`});o.push({decl:d,binding:f})}for(let d=0;d<o.length;d++)for(let f=d+1;f<o.length;f++){const h=o[d],g=o[f];if(!(h.binding.buffer!==g.binding.buffer||!(h.decl.kind==="storage"||g.decl.kind==="storage"))){if(h.decl.kind!==g.decl.kind)throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind one buffer with different access modes (writable usage next to another usage)`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"one access mode per buffer when a slot is read_write",reason:"usage"});if(aS(h.binding,g.binding))throw new S("E_INVALID_ARGUMENT",`${t}: "${h.decl.name}" and "${g.decl.name}" bind intersecting ranges of one read_write buffer`,{argument:"aliasing",value:[h.decl.name,g.decl.name],expected:"disjoint ranges",reason:"range"})}}const s=o.map(({binding:d})=>`${iS(d.buffer)}:${d.offset}:${d.size}`).join("|"),i=this.cache.get(s);if(i!==void 0)return this.cache.delete(s),this.cache.set(s,i),i;const a=new Map(o.map(({decl:d,binding:f})=>[d.name,f])),c=this.layouts.map((d,f)=>this.device.createBindGroup({label:`${t}/${f}`,layout:d,entries:this.groups[f].map(h=>{const g=a.get(h.name);return{binding:h.binding,resource:{buffer:g.buffer,offset:g.offset,size:g.size}}})})),l=[];this.dynamicCounts.forEach((d,f)=>{d>0&&l.push(f)});const u=Object.freeze({kernel:this,bindGroups:Object.freeze(c),dynamicGroups:Object.freeze(l)});return this.cache.set(s,u),this.cache.size>sS&&this.cache.delete(this.cache.keys().next().value),u}dispatch(e,t,r,o){this.check(t,o),r.x!==0&&(this.setUp(e,t,o),e.dispatchWorkgroups(r.x,r.y,r.z))}dispatchIndirect(e,t,r,o,s){if(this.check(t,s),!Number.isInteger(o)||o<0||(o+1)*dl>r.size)throw new S("E_INVALID_ARGUMENT",`${this.spec.id}: args slot ${o} is outside the binding`,{argument:"slot",value:o,expected:`0 <= slot < ${Math.floor(r.size/dl)}`});this.setUp(e,t,s),e.dispatchWorkgroupsIndirect(r.buffer,r.offset+dl*o)}check(e,t){const{id:r}=this.spec;if(e.kernel!==this)throw new S("E_INVALID_ARGUMENT",`${r}: the bound kernel belongs to "${e.kernel.spec.id}"`,{argument:"bound",value:e.kernel.spec.id,expected:r});if(t!==void 0&&t.length!==e.dynamicGroups.length)throw new S("E_INVALID_ARGUMENT",`${r}: ${t.length} dynamic offsets for ${e.dynamicGroups.length} dynamic groups`,{argument:"dynamicOffsets",value:t.length,expected:e.dynamicGroups.length})}setUp(e,t,r){e.setPipeline(this.pipeline);let o=0;t.bindGroups.forEach((s,i)=>{const a=this.dynamicCounts[i];if(a>0){const c=r?.[o]??0;o+=1;const l=[];for(let u=0;u<a;u++)l.push(c);e.setBindGroup(i,s,l)}else e.setBindGroup(i,s)})}invalidate(){this.cache.clear()}}const Se=Object.freeze({MAP_READ:1,MAP_WRITE:2,COPY_SRC:4,COPY_DST:8,INDEX:16,VERTEX:32,UNIFORM:64,STORAGE:128,INDIRECT:256,QUERY_RESOLVE:512}),Xw=Object.freeze({READ:1,WRITE:2}),Qw=Object.freeze({VERTEX:1,FRAGMENT:2,COMPUTE:4});function Tr(n){if(!Number.isFinite(n))throw new S("E_INVALID_ARGUMENT",`wgslF32Literal: ${n} is not a finite number`,{argument:"value",value:n,expected:"a finite number"});const e=String(n);return/[.e]/.test(e)?e:`${e}.0`}const Jw=`// ---- prelude: constants, standard overrides, helpers (every module receives this text first)
2
+ const INVALID_INDEX: u32 = ${x}u;
3
+ const U32_MAX: u32 = ${Ve}u;
4
+ const F32_INF_BITS: u32 = ${ho}u;
5
+ const F32_SIGN_BIT: u32 = ${Vk}u;
6
+ const MAX_WORKGROUPS_PER_DIM: u32 = ${lo}u;
7
+ const EXACT_TILES_PER_PASS: u32 = ${Nw}u;
8
+ const FA2_DIST_FLOOR: f32 = ${Tr(Ek)};
9
+ const FA2_DIST_FLOOR_SQ: f32 = ${Tr(_k)};
10
+ const FA2_COINCIDENT_SQ: f32 = ${Tr(Ik)};
11
+ const FA2_FLAG_FIRST: u32 = ${ol}u;
12
+ const FA2_FLAG_ADAPTIVE: u32 = ${Tw}u;
13
+ const FR_COOLING_STEP: f32 = ${Tr(Sk)};
14
+ const FR_COOLING_PATIENCE: u32 = ${Pk}u;
15
+ const GRID_HUB_CELL: u32 = ${Dw}u;
16
+ const GRID_EXTENT_FLOOR: f32 = ${Tr(Lw)};
17
+ const GRID_BBOX_MARGIN: f32 = ${Tr(Mw)};
18
+ const RADIX_BINS: u32 = ${Ii}u;
19
+ const RADIX_DIGIT_MASK: u32 = ${Ii-1}u;
20
+ const APSP_TILE: u32 = ${il}u;
21
+ const GROUP_HASH_LOAD_FACTOR: u32 = ${Fw}u;
22
+ const TRIANGLE_BINARY_SEARCH_RATIO: u32 = ${qk}u;
23
+ const BC_SIGMA_EXPONENT_CAP: i32 = ${zk}i;
24
+ const F32_MAX: f32 = 0x1.fffffep+127;
25
+ override WG: u32 = ${nl}u;
26
+ override USE_PERM: bool = false;
27
+ override HAS_WEIGHTS: bool = false;
28
+ override SUBGROUP_MIN: u32 = 4u;
29
+ override SUBGROUP_MAX: u32 = 0u;
30
+
31
+ fn linear_id(wid: vec3<u32>, lid: u32) -> u32 { return (wid.x + wid.y * MAX_WORKGROUPS_PER_DIM) * WG + lid; }
32
+ fn group_id(wid: vec3<u32>) -> u32 { return wid.x + wid.y * MAX_WORKGROUPS_PER_DIM; }
33
+ // betweenness: the power of two the counts of depth L + 1 are divided by, from the f32 bits of depth L's largest count
34
+ fn sigma_shift(maxBits: u32) -> i32 { return max(0i, i32((maxBits >> 23u) & 0xffu) - 127i - BC_SIGMA_EXPONENT_CAP); }
35
+ fn lowbias32(x0: u32) -> u32 {
36
+ var x = x0;
37
+ x = x ^ (x >> 16u);
38
+ x = x * 0x7feb352du;
39
+ x = x ^ (x >> 15u);
40
+ x = x * 0x846ca68bu;
41
+ x = x ^ (x >> 16u);
42
+ return x;
43
+ }
44
+ fn mask_bit(w: u32, i: u32) -> bool { return ((w >> (i & 31u)) & 1u) == 1u; }
45
+ fn unpack_u8(w: u32, i: u32) -> u32 { return (w >> (8u * (i & 3u))) & 0xFFu; }
46
+ fn pair_hash(i: u32, j: u32) -> u32 { return lowbias32((min(i, j) * 0x9E3779B9u) ^ max(i, j)); }
47
+ fn order_key(w: f32) -> u32 {
48
+ let raw = bitcast<u32>(w);
49
+ let bits = select(raw, 0u, raw == F32_SIGN_BIT);
50
+ return select(bits | F32_SIGN_BIT, ~bits, (bits & F32_SIGN_BIT) != 0u);
51
+ }
52
+ fn hash_unit(h: u32) -> f32 { return f32(h >> 8u) * (1.0 / 16777216.0); }
53
+ fn hash_dir(h: u32, dim: u32) -> vec3f {
54
+ let phi = 6.283185307179586 * hash_unit(h);
55
+ if (dim == 2u) { return vec3f(cos(phi), sin(phi), 0.0); }
56
+ let z = 2.0 * hash_unit(lowbias32(h ^ 0x5bd1e995u)) - 1.0;
57
+ let r = sqrt(max(0.0, 1.0 - z * z));
58
+ return vec3f(r * cos(phi), r * sin(phi), z);
59
+ }
60
+ fn kick_dir(i: u32, j: u32, dim: u32) -> vec3f {
61
+ let d = hash_dir(pair_hash(i, j), dim);
62
+ return select(d, -d, i > j);
63
+ }`;Jw.split(`
64
+ `).length;const lS=`var<workgroup> wg_scratch_v: array<vec4f, WG>;
65
+ var<workgroup> wg_scratch_u: array<u32, WG>;
66
+ fn combine_v(a: vec4f, b: vec4f, op: u32) -> vec4f {
67
+ if (op == 1u) { return min(a, b); }
68
+ if (op == 2u) { return max(a, b); }
69
+ return a + b;
70
+ }
71
+ fn combine_u(a: u32, b: u32, op: u32) -> u32 {
72
+ if (op == 1u) { return min(a, b); }
73
+ if (op == 2u) { return max(a, b); }
74
+ return a + b;
75
+ }
76
+ fn wg_reduce_vec4(v: vec4f, lid: u32, op: u32) -> vec4f {
77
+ workgroupBarrier();
78
+ wg_scratch_v[lid] = v;
79
+ workgroupBarrier();
80
+ for (var s = WG / 2u; s > 0u; s = s >> 1u) {
81
+ if (lid < s) { wg_scratch_v[lid] = combine_v(wg_scratch_v[lid], wg_scratch_v[lid + s], op); }
82
+ workgroupBarrier();
83
+ }
84
+ let total = wg_scratch_v[0];
85
+ workgroupBarrier();
86
+ return total;
87
+ }
88
+ fn wg_reduce_u32(v: u32, lid: u32, op: u32) -> u32 {
89
+ workgroupBarrier();
90
+ wg_scratch_u[lid] = v;
91
+ workgroupBarrier();
92
+ for (var s = WG / 2u; s > 0u; s = s >> 1u) {
93
+ if (lid < s) { wg_scratch_u[lid] = combine_u(wg_scratch_u[lid], wg_scratch_u[lid + s], op); }
94
+ workgroupBarrier();
95
+ }
96
+ let total = wg_scratch_u[0];
97
+ workgroupBarrier();
98
+ return total;
99
+ }
100
+ fn wg_scan_u32(v: u32, lid: u32) -> u32 {
101
+ workgroupBarrier();
102
+ wg_scratch_u[lid] = v;
103
+ workgroupBarrier();
104
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan (scan-block's body); uniform: every lane runs every round
105
+ var t = 0u;
106
+ if (lid >= s) { t = wg_scratch_u[lid - s]; }
107
+ workgroupBarrier();
108
+ wg_scratch_u[lid] = wg_scratch_u[lid] + t;
109
+ workgroupBarrier();
110
+ }
111
+ let inclusive = wg_scratch_u[lid];
112
+ workgroupBarrier(); // the scratch is free for the next call
113
+ return inclusive;
114
+ }
115
+ fn wg_reduce_f32(v: f32, lid: u32, op: u32) -> f32 { return wg_reduce_vec4(vec4f(v, 0.0, 0.0, 0.0), lid, op).x; }`,uS=`override SG_SLOTS: u32 = (WG + SUBGROUP_MIN - 1u) / SUBGROUP_MIN; // one slot per subgroup; the count is largest when the compiler picks the SMALLEST size
116
+ var<workgroup> sg_counter: atomic<u32>;
117
+ var<workgroup> sg_val_v: array<vec4f, SG_SLOTS>;
118
+ var<workgroup> sg_val_u: array<u32, SG_SLOTS>;
119
+ var<workgroup> sg_key: array<u32, SG_SLOTS>;
120
+ var<workgroup> sg_sorted_v: array<vec4f, SG_SLOTS>;
121
+ var<workgroup> sg_sorted_u: array<u32, SG_SLOTS>;
122
+ fn combine_v(a: vec4f, b: vec4f, op: u32) -> vec4f {
123
+ if (op == 1u) { return min(a, b); }
124
+ if (op == 2u) { return max(a, b); }
125
+ return a + b;
126
+ }
127
+ fn combine_u(a: u32, b: u32, op: u32) -> u32 {
128
+ if (op == 1u) { return min(a, b); }
129
+ if (op == 2u) { return max(a, b); }
130
+ return a + b;
131
+ }
132
+ fn wg_reduce_vec4(v: vec4f, lid: u32, op: u32) -> vec4f {
133
+ workgroupBarrier();
134
+ if (lid == 0u) { atomicStore(&sg_counter, 0u); }
135
+ workgroupBarrier();
136
+ let s_add = subgroupAdd(v);
137
+ let s_min = subgroupMin(v);
138
+ let s_max = subgroupMax(v);
139
+ var partial = s_add;
140
+ if (op == 1u) { partial = s_min; }
141
+ if (op == 2u) { partial = s_max; }
142
+ let key = subgroupMin(lid); // the smallest local id of this subgroup: a stable identity without @builtin(subgroup_id)
143
+ var slot = 0u;
144
+ if (subgroupElect()) { slot = atomicAdd(&sg_counter, 1u); } // D16: the elected lane takes a slot from the counter
145
+ slot = subgroupBroadcast(slot, 0u); // and broadcasts it (lane 0 is the elected lane in uniform control flow)
146
+ if (subgroupElect()) { sg_val_v[slot] = partial; sg_key[slot] = key; }
147
+ workgroupBarrier();
148
+ let count = atomicLoad(&sg_counter);
149
+ if (lid < count) { // rank the slots by key so the final sum has a fixed order (11.9 item 4)
150
+ let mine = sg_key[lid];
151
+ var rank = 0u;
152
+ for (var k = 0u; k < count; k = k + 1u) { if (sg_key[k] < mine) { rank = rank + 1u; } }
153
+ sg_sorted_v[rank] = sg_val_v[lid];
154
+ }
155
+ workgroupBarrier();
156
+ var total = sg_sorted_v[0];
157
+ for (var k = 1u; k < count; k = k + 1u) { total = combine_v(total, sg_sorted_v[k], op); }
158
+ workgroupBarrier();
159
+ return total;
160
+ }
161
+ fn wg_reduce_u32(v: u32, lid: u32, op: u32) -> u32 {
162
+ workgroupBarrier();
163
+ if (lid == 0u) { atomicStore(&sg_counter, 0u); }
164
+ workgroupBarrier();
165
+ let s_add = subgroupAdd(v);
166
+ let s_min = subgroupMin(v);
167
+ let s_max = subgroupMax(v);
168
+ var partial = s_add;
169
+ if (op == 1u) { partial = s_min; }
170
+ if (op == 2u) { partial = s_max; }
171
+ let key = subgroupMin(lid);
172
+ var slot = 0u;
173
+ if (subgroupElect()) { slot = atomicAdd(&sg_counter, 1u); }
174
+ slot = subgroupBroadcast(slot, 0u);
175
+ if (subgroupElect()) { sg_val_u[slot] = partial; sg_key[slot] = key; }
176
+ workgroupBarrier();
177
+ let count = atomicLoad(&sg_counter);
178
+ if (lid < count) {
179
+ let mine = sg_key[lid];
180
+ var rank = 0u;
181
+ for (var k = 0u; k < count; k = k + 1u) { if (sg_key[k] < mine) { rank = rank + 1u; } }
182
+ sg_sorted_u[rank] = sg_val_u[lid];
183
+ }
184
+ workgroupBarrier();
185
+ var total = sg_sorted_u[0];
186
+ for (var k = 1u; k < count; k = k + 1u) { total = combine_u(total, sg_sorted_u[k], op); }
187
+ workgroupBarrier();
188
+ return total;
189
+ }
190
+ fn wg_scan_u32(v: u32, lid: u32) -> u32 {
191
+ workgroupBarrier();
192
+ if (lid == 0u) { atomicStore(&sg_counter, 0u); }
193
+ workgroupBarrier();
194
+ let inSub = subgroupExclusiveAdd(v) + v; // the lane's inclusive sum within its subgroup
195
+ let total = subgroupAdd(v);
196
+ let key = subgroupMin(lid); // the subgroup's identity: its smallest local id (D16)
197
+ var slot = 0u;
198
+ if (subgroupElect()) { slot = atomicAdd(&sg_counter, 1u); }
199
+ slot = subgroupBroadcast(slot, 0u);
200
+ if (subgroupElect()) { sg_val_u[slot] = total; sg_key[slot] = key; }
201
+ workgroupBarrier();
202
+ let count = atomicLoad(&sg_counter);
203
+ var carry = 0u; // the totals of every subgroup whose key is below this lane's: LANE order, whatever order the slots were taken in
204
+ for (var k = 0u; k < count; k = k + 1u) { if (sg_key[k] < key) { carry = carry + sg_val_u[k]; } }
205
+ workgroupBarrier(); // the slots are free for the next call
206
+ return inSub + carry;
207
+ }
208
+ fn wg_reduce_f32(v: f32, lid: u32, op: u32) -> f32 { return wg_reduce_vec4(vec4f(v, 0.0, 0.0, 0.0), lid, op).x; }`,dS=["wg_reduce_f32","wg_reduce_u32","wg_reduce_vec4","wg_scan_u32"],Zw=Object.freeze(`NULL Self abstract active alignas alignof as asm asm_fragment async attribute auto await become cast catch class
209
+ co_await co_return co_yield coherent column_major common compile compile_fragment concept const_cast consteval
210
+ constexpr constinit crate debugger decltype delete demote demote_to_helper do dynamic_cast enum explicit export
211
+ extends extern external fallthrough filter final finally friend from fxgroup get goto groupshared highp impl
212
+ implements import inline instanceof interface layout lowp macro macro_rules match mediump meta mod module move
213
+ mut mutable namespace new nil noexcept noinline nointerpolation non_coherent noncoherent noperspective null
214
+ nullptr of operator package packoffset partition pass patch pixelfragment precise precision premerge priv
215
+ protected pub public readonly ref regardless register reinterpret_cast require resource restrict self set shared
216
+ sizeof smooth snorm static static_assert static_cast std subroutine super target template this thread_local
217
+ throw trait try type typedef typeid typename typeof union unless unorm unsafe unsized use using varying virtual
218
+ volatile wgsl where with writeonly yield`.trim().split(/\s+/)),fS=["WG","USE_PERM","HAS_WEIGHTS","SUBGROUP_MIN","SUBGROUP_MAX"],hS=Object.freeze({WG:"u32",USE_PERM:"bool",HAS_WEIGHTS:"bool",SUBGROUP_MIN:"u32",SUBGROUP_MAX:"u32"}),gS=Object.freeze(["subgroups"]),wS=4,pS=new Set(["u32","i32","f32","f16","bool","vec2f","vec3f","vec4f","vec2u","vec3u","vec4u","vec2i","vec3i","vec4i","vec2h","vec3h","vec4h"]),mS=/^(vec[234]|mat[234]x[234]|atomic|array)</,ep=/^[A-Za-z_]\w*$/,yS=Object.freeze({storage:"var<storage, read_write>","storage-ro":"var<storage, read>",uniform:"var<uniform>"}),fl=new Set(Zw),bS=/\/\/@@(\w+)@@/,vS=new RegExp("(?<!\\w)[A-Za-z_]\\w*","g"),AS=/@compute\b/g,ES=/\bfn\s+([A-Za-z_]\w*)/;function _t(n,e,t){return new S("E_SHADER_COMPILE",`${n}: ${t}`,{id:n,stage:"compose",slot:e})}function tp(n){return n.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"")}function _S(n){const e=n.trim(),t=e.startsWith("array<")?e.slice(6).replace(/\s*(,[^>]*)?>\s*$/,""):e;return pS.has(t)||mS.test(t)?null:t}function np(n,e,t,r){if(!(t==="bool"?typeof r=="boolean":typeof r=="number"&&Number.isFinite(r)&&(t==="f32"||Number.isInteger(r)&&r>=0)))throw _t(n,`override:${e}`,`override ${e} (${t}) cannot take the value ${String(r)}`)}function IS(n){if(n.type==="bool")return n.default?"true":"false";const e=n.default;return n.type==="u32"?`${e}u`:Tr(e)}function kS(n){const e=yS[n.kind];return`@group(${n.group}) @binding(${n.binding}) ${e} ${n.name}: ${n.wgslType};`}function SS(n){const e=tp(n),t=[...e.matchAll(AS)];if(t.length!==1||t[0].index===void 0)return null;const r=ES.exec(e.slice(t[0].index));return r===null?null:r[1]}function PS(n){const e=n.bindings.reduce((o,s)=>Math.max(o,s.group),-1),t=new Map(n.uniforms.map(o=>[o.name,o])),r=[];for(let o=0;o<=e;o++){const s=n.bindings.filter(i=>i.group===o).sort((i,a)=>i.binding-a.binding).map(i=>{if(i.kind==="uniform"){const a=t.get(i.wgslType),c={type:"uniform",hasDynamicOffset:!0};return a!==void 0&&(c.minBindingSize=a.byteLength),{binding:i.binding,visibility:Qw.COMPUTE,buffer:c}}return{binding:i.binding,visibility:Qw.COMPUTE,buffer:{type:i.kind==="storage"?"storage":"read-only-storage"}}});r.push({entries:s})}return r}function xS(n){const{id:e}=n;for(const i of n.needs)if(!gS.includes(i))throw _t(e,`needs:${i}`,`unknown feature "${i}" in needs`);const t=new Map;for(const i of n.overrideDecls){if(!ep.test(i.name)||fl.has(i.name))throw _t(e,`override:${i.name}`,`override name "${i.name}" is not a usable identifier`);if(fS.includes(i.name)||t.has(i.name))throw _t(e,`override:${i.name}`,`override "${i.name}" is declared twice (the prelude declares the standard ones)`);np(e,i.name,i.type,i.default),t.set(i.name,i.type)}for(const[i,a]of Object.entries(n.overrides)){const l=hS[i]??t.get(i);if(l===void 0)throw _t(e,`override:${i}`,`override "${i}" is neither a standard override nor declared in overrideDecls`);np(e,i,l,a)}const r=new Set,o=new Set,s=new Set(n.uniforms.map(i=>i.name));for(const i of n.bindings){if(!ep.test(i.name)||fl.has(i.name))throw _t(e,`binding:${i.name}`,`binding name "${i.name}" is not a usable identifier`);const a=`${i.group}.${i.binding}`;if(r.has(a))throw _t(e,`binding:${i.name}`,`two bindings share group ${i.group} binding ${i.binding}`);if(o.has(i.name))throw _t(e,`binding:${i.name}`,`two bindings share the name "${i.name}"`);r.add(a),o.add(i.name);const c=_S(i.wgslType);if(c!==null&&!s.has(c))throw _t(e,`type:${c}`,`binding "${i.name}" names struct "${c}" but no block in spec.uniforms declares it`)}}function CS(n){const{id:e}=n;let{body:t}=n;for(const[o,s]of Object.entries(n.snippets??{})){const i=`//@@${o}@@`;if(!t.includes(i))throw _t(e,`snippet:${o}`,`snippet "${o}" has no ${i} marker in the body`);t=t.split(i).join(s)}const r=bS.exec(t);if(r!==null)throw _t(e,`marker:${r[1]}`,`marker //@@${r[1]}@@ is not filled by any snippet`);return t}function NS(n,e){const{id:t}=n;for(const s of["@group(","override "])if(e.includes(s))throw _t(t,`body:${s}`,`a body must not contain "${s}" (the composer emits those lines)`);const r=tp(e),o=dS;for(const s of r.matchAll(vS)){const i=s[0];if(fl.has(i))throw _t(t,`reserved:${i}`,`"${i}" is a WGSL reserved word (spec 16.2) and cannot be an identifier`);if(o.includes(i)&&!n.needs.includes("subgroups"))throw _t(t,`helper:${i}`,`the body calls ${i} but spec.needs does not list "subgroups"`)}}function TS(n,e){xS(n);const t=SS(n.body);if(t===null)throw _t(n.id,"entry","a body must carry exactly one @compute attribute followed by `fn <name>`");const r=CS(n);NS(n,r);const o=n.needs.includes("subgroups"),s=o&&e.features.has("subgroups"),i={...n.overrides};i.WG===void 0&&(i.WG=ll(e)),s&&(i.SUBGROUP_MAX=e.subgroupMaxSize,i.SUBGROUP_MIN=Math.max(wS,e.subgroupMinSize));const a=[];s&&a.push("enable subgroups;"),a.push(Jw);for(const u of n.overrideDecls)a.push(`override ${u.name}: ${u.type} = ${IS(u)};`);for(const u of n.uniforms)a.push(u.wgsl);o&&a.push(s?uS:lS);for(const u of n.bindings)a.push(kS(u));const c=a.join(`
219
+ `),l=`${c}
220
+ ${r}`;return Object.freeze({id:n.id,code:l,bodyLine:c.split(`
221
+ `).length+1,overrides:Object.freeze(i),constants:Object.freeze(OS(l,i)),entryPoint:t,subgroups:s})}function OS(n,e){const t=n.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ").replace(/^\s*override\s+\w+\s*:[^\n]*$/gm," "),r={};for(const[o,s]of Object.entries(e))new RegExp(String.raw`\b${o}\b`).test(t)&&(r[o]=s);return r}function Ci(n){if(Array.isArray(n))return`[${n.map(e=>Ci(e)).join(",")}]`;if(typeof n=="object"&&n!==null){const e=n;return`{${Object.keys(e).sort().map(o=>`${JSON.stringify(o)}:${Ci(e[o])}`).join(",")}}`}return JSON.stringify(n)}function $S(n){if(n===void 0||Object.keys(n).length===0)return"0";const e=Ci(n);let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function RS(n,e){const t=n.needs.filter(r=>e.features.has(r)).join(",");return`${n.id}|${Ci(n.overrides)}|${t}|${$S(n.snippets)}`}function DS(n){return n instanceof Error?n.message:String(n)}class LS{constructor(e,t){this.pending=new Map,this.entries=new Map,this.order=[],this.disposed=!1,this.device=e,this.caps=t}key(e){return RS(e,this.caps)}async get(e){return(await this.entry(e)).pipeline}async kernel(e){return(await this.entry(e)).kernel}async warm(e){await Promise.all(e.map(t=>this.entry(t)))}get size(){return this.entries.size}keys(){return this.order.filter(e=>this.entries.has(e))}layoutsOf(e){return this.entries.get(e)?.layouts??null}dispose(){this.disposed=!0,this.pending.clear(),this.entries.clear(),this.order.length=0}entry(e){if(this.disposed)return Promise.reject(new S("E_DISPOSED","PipelineCache: disposed",{label:"PipelineCache"}));const t=this.key(e),r=this.pending.get(t);if(r!==void 0)return r;this.order.push(t);const o=this.compile(e,t).then(s=>(this.disposed||this.entries.set(t,s),s),s=>{this.pending.delete(t);const i=this.order.indexOf(t);throw i>=0&&this.order.splice(i,1),s});return this.pending.set(t,o),o}async compile(e,t){const r=TS(e,this.caps),{device:o}=this,s=`${e.id}|pipeline`;o.pushErrorScope("validation");const i=o.createShaderModule({code:r.code,label:e.id}),a=PS(e).map((p,m)=>o.createBindGroupLayout({...p,label:`${e.id}/layout${m}`})),c=o.createPipelineLayout({bindGroupLayouts:a,label:`${e.id}|layout`}),l=o.popErrorScope(),u=await i.getCompilationInfo(),d=await l,f=u.messages.filter(p=>p.type==="error");if(f.length>0){const p=r.bodyLine-1;throw new S("E_SHADER_COMPILE",`${e.id}: WGSL compilation failed (${f.length} error(s))`,{id:e.id,stage:"compile",messages:Zk(u,p),lines:f.map(m=>m.lineNum-p)})}if(d!==null)throw new S("E_VALIDATION",`${e.id}: ${d.message}`,{label:s,message:d.message});const h={};for(const[p,m]of Object.entries(r.constants))typeof m=="boolean"?h[p]=m?1:0:h[p]=m;let g;try{g=await o.createComputePipelineAsync({label:t,layout:c,compute:{module:i,entryPoint:r.entryPoint,constants:h}})}catch(p){const m=DS(p);throw new S("E_VALIDATION",`${e.id}: pipeline creation failed: ${m}`,{label:s,message:m})}const w=new cS(o,e,r,g,a);return{key:t,composed:r,pipeline:g,layouts:a,kernel:w}}}class MS{constructor(e,t,r,o){this.labels=new WeakMap,this.partialRequests=new WeakSet,this.pending=[],this.cursor=0,this.refused=0,this.destroyed=!1;const s=o??yk;this.quantised=r,this.slots=s;const i=t&&s>=2&&e.features.has("timestamp-query");this.enabled=i,i?(this.querySet=e.createQuerySet({label:"profiler/timestamps",type:"timestamp",count:s}),this.resolveBuffer=e.createBuffer({label:"profiler/resolve",size:s*8,usage:Se.QUERY_RESOLVE|Se.COPY_SRC})):(this.querySet=null,this.resolveBuffer=null)}beginPass(e){if(this.querySet===null||this.destroyed)return;if(this.cursor+2>this.slots){this.refused++;return}const t=this.cursor;return this.cursor+=2,this.pending.push({label:e,begin:t}),{querySet:this.querySet,beginningOfPassWriteIndex:t,endOfPassWriteIndex:t+1}}resolveInto(e){if(this.querySet===null||this.resolveBuffer===null||this.destroyed||this.pending.length===0)return null;const t=this.cursor;e.resolveQuerySet(this.querySet,0,t,this.resolveBuffer);const r=e.readback(this.resolveBuffer,0,t*8);return this.labels.set(r,this.pending.map(o=>o.label)),this.refused>0&&this.partialRequests.add(r),this.pending=[],this.cursor=0,this.refused=0,r}partial(e){return this.partialRequests.has(e)}timings(e,t){const r=this.labels.get(t);if(r===void 0)return[];const o=new DataView(e),s=[];for(let i=0;i<r.length;i++){const a=t.offset+i*16;if(a+16>e.byteLength)break;const c=o.getBigUint64(a,!0),l=o.getBigUint64(a+8,!0);s.push({label:r[i],ns:Number(l-c)})}return s}destroy(){this.destroyed||(this.destroyed=!0,this.pending=[],this.cursor=0,this.refused=0,this.querySet!==null&&this.querySet.destroy(),this.resolveBuffer!==null&&this.resolveBuffer.destroy())}}class US{constructor(e){this.buffers=new Set,this.released=!1,this.pool=e}storage(e,t){return this.acquire(e,Se.STORAGE|Se.COPY_SRC|Se.COPY_DST,t)}uniform(e,t){return this.acquire(e,Se.UNIFORM|Se.COPY_DST,t)}acquire(e,t,r){if(this.released)throw new S("E_DISPOSED",`lease already released: cannot acquire "${r}"`,{label:r});const o=this.pool.acquire(e,t,r);return this.buffers.add(o),o}release(){if(this.released)return;this.released=!0;const e=[...this.buffers];this.buffers.clear();for(const t of e)try{this.pool.release(t)}catch(r){if(!xi(r,"E_DISPOSED"))throw r}}get count(){return this.buffers.size}}function rp(n,e){return`${n}:${e}`}class hl{constructor(e,t,r,o){this.idle=new Map,this.live=new Map,this.liveBytesValue=0,this.idleBytesValue=0,this.disposed=!1,this.allocator=t,this.maxBufferSize=r-r%4,this.maxIdlePerClass=o?.maxIdlePerClass??bk}static sizeClass(e){if(!Number.isInteger(e)||e<=0)throw new S("E_INVALID_ARGUMENT","byteLength: expected a positive integer",{argument:"byteLength",value:e,expected:"a positive integer"});if(e>Ak)return Math.ceil(e/Pw)*Pw;let t=vk;for(;t<e;)t*=2;return t}acquire(e,t,r){if(this.disposed)throw new S("E_DISPOSED","the buffer pool was disposed",{label:"pool"});const o=hl.sizeClass(e);if(e>this.maxBufferSize)throw new S("E_TOO_LARGE",`pool: ${e} bytes exceed the device maxBufferSize of ${this.maxBufferSize} bytes`,{needed:e,limit:this.maxBufferSize,path:"pool",algorithm:null});const s=Math.min(o,this.maxBufferSize),i=rp(s,t);let c=this.idle.get(i)?.pop();return c===void 0?c=this.allocator.createBuffer({label:r,size:s,usage:t}):(this.idleBytesValue-=s,c.label=r),this.live.set(c,{sizeClass:s,usage:t}),this.liveBytesValue+=s,c}release(e){if(this.disposed)return;const t=this.live.get(e);if(t===void 0)throw new S("E_INVALID_ARGUMENT","buffer: not a live buffer of this pool",{argument:"buffer",value:e.label,expected:"a buffer acquired from this pool and not yet released"});this.live.delete(e),this.liveBytesValue-=t.sizeClass;const r=rp(t.sizeClass,t.usage);let o=this.idle.get(r);if(o===void 0&&(o=[],this.idle.set(r,o)),o.length>=this.maxIdlePerClass){this.allocator.destroy(e);return}o.push(e),this.idleBytesValue+=t.sizeClass}trim(){for(const e of this.idle.values())for(const t of e)this.allocator.destroy(t);this.idle.clear(),this.idleBytesValue=0}destroyAll(){this.trim();for(const e of this.live.keys())this.allocator.destroy(e);this.live.clear(),this.liveBytesValue=0,this.disposed=!0}lease(){return new US(this)}get liveBytes(){return this.liveBytesValue}get idleBytes(){return this.idleBytesValue}}const FS=4*1024*1024,BS=Se.MAP_READ|Se.COPY_DST,op=256;function zS(n){return Object.prototype.toString.call(n)==="[object SharedArrayBuffer]"}function tn(n,e,t){return new S("E_INVALID_ARGUMENT",`${n}: expected ${t}`,{argument:n,value:e,expected:t})}class GS{constructor(e,t,r){this.ring=[],this.disposed=!1;const o=r?.slotBytes??FS;if(!Number.isInteger(o)||o<=0||o%4!==0)throw tn("slotBytes",o,"a positive multiple of 4");const s=r?.slots??mk;if(!Number.isInteger(s)||s<0)throw tn("slots",s,"a non-negative integer");this.device=e,this.allocator=t,this.slotBytes=o;for(let i=0;i<s;i++)this.addSlot(o)}async read(e,t,r,o){this.assertLive();const s=o??0;if(!Number.isInteger(t)||t<=0||t%4!==0)throw tn("byteLength",t,"a positive multiple of 4");if(!Number.isInteger(s)||s<0||s%4!==0)throw tn("srcOffset",s,"a non-negative multiple of 4");if(s+t>e.size)throw tn("byteLength",t,`srcOffset + byteLength <= src.size (${e.size})`);if((e.usage&Se.COPY_SRC)===0)throw tn("src",e.label,"a buffer with COPY_SRC usage");let i,a;if(r===void 0)i=new ArrayBuffer(t),a=new Uint8Array(i);else{if(zS(r.buffer))throw tn("dest","SharedArrayBuffer","a view over a plain ArrayBuffer");if(r.byteLength<t)throw tn("dest",r.byteLength,`at least ${t} bytes`);i=r.buffer,a=new Uint8Array(i,r.byteOffset,t)}let c=0;for(;c<t;){const l=Math.min(this.slotBytes,t-c),u=this.borrowSlot(l),d=this.ring[u.index];try{const f=this.device.createCommandEncoder({label:"readback"});f.copyBufferToBuffer(e,s+c,u.buffer,0,l),this.device.queue.submit([f.finish()]),await this.map(d,l),a.set(new Uint8Array(u.buffer.getMappedRange(0,l)),c)}finally{this.returnSlot(u)}c+=l}return i}async readU32(e,t){const r=await this.read(e,4,void 0,t);return new Uint32Array(r)[0]}borrowSlot(e){if(this.assertLive(),!Number.isInteger(e)||e<=0)throw tn("byteLength",e,"a positive integer");for(const o of this.ring)if(!o.borrowed&&o.slot.capacity>=e)return o.borrowed=!0,o.slot;const t=Math.max(this.slotBytes,Math.ceil(e/op)*op),r=this.addSlot(t);return r.borrowed=!0,r.slot}mapSlot(e,t){this.assertLive();const r=this.borrowedEntry(e);if(r.mapPending||r.mapped)throw tn("slot",e.index,"a borrowed slot that is not mapped and has no map pending");return this.track(r,e.buffer.mapAsync(Xw.READ,0,t))}returnSlot(e){if(this.disposed)return;const t=this.borrowedEntry(e);if(t.mapPending){t.returnRequested=!0;return}this.finishReturn(t)}borrowedEntry(e){const t=this.ring[e.index];if(t?.slot!==e||!t.borrowed)throw tn("slot",e.index,"a slot borrowed from this ring and not yet returned");return t}finishReturn(e){const t=e.slot.buffer.mapState;(t===void 0?e.mapped:t!=="unmapped")&&e.slot.buffer.unmap(),e.mapped=!1,e.borrowed=!1,e.returnRequested=!1}track(e,t){e.mapPending=!0;const r=o=>{if(e.mapPending=!1,e.mapped=o,this.disposed){o&&e.slot.buffer.unmap(),this.destroySlot(e),e.mapped=!1;return}e.returnRequested&&this.finishReturn(e)};return t.then(()=>{r(!0)},()=>{r(!1)}),t}get slots(){return this.ring.length}get borrowed(){let e=0;for(const t of this.ring)t.borrowed&&e++;return e}destroyAll(){for(const e of this.ring)e.mapPending||this.destroySlot(e);this.ring.length=0,this.disposed=!0}destroySlot(e){e.tracked?this.allocator.destroy(e.slot.buffer):e.slot.buffer.destroy()}addSlot(e){const t=this.ring.length,r={label:`readback:slot:${t}`,size:e,usage:BS},o=e>=Sw,s=o?this.allocator.createBuffer(r):this.device.createBuffer(r),i={slot:Object.freeze({index:t,buffer:s,capacity:e}),borrowed:!1,mapped:!1,mapPending:!1,returnRequested:!1,tracked:o};return this.ring.push(i),i}async map(e,t){let r=!1,o=null;try{await this.track(e,e.slot.buffer.mapAsync(Xw.READ,0,t)),r=!0}catch(s){o=s}if(this.disposed)throw new S("E_DISPOSED","the readback ring was disposed while a read was pending",{label:"readback"});if(!r){const s=o instanceof Error?o.message:String(o);throw new S("E_DEVICE_LOST",`mapAsync rejected: ${s}`,{reason:"mapAsync",message:s})}}assertLive(){if(this.disposed)throw new S("E_DISPOSED","the readback ring was disposed",{label:"readback"})}}const WS=Object.freeze(["rowPtr","colIdx","weights","arcToEdge","edgeToArc"]),VS=new Set(["colIdx","weights","arcToEdge"]);function jS(n){const e=n.arcCount,t=n.flags.arcToEdgeIsIdentity;return{rowPtr:4*(n.nodeCount+1),colIdx:4*e,weights:n.flags.weighted&&e>0?4*e:0,arcToEdge:!t&&e>0?4*e:0,edgeToArc:!t&&n.edgeCount>0?4*n.edgeCount:0}}function qS(n,e){const t=new Set(n);return t.add("rowPtr"),WS.filter(r=>t.has(r)&&e[r]>0)}function gl(n){return n-n%uo}function wl(n,e,t){return new S("E_TOO_LARGE",`${t}: ${n} bytes exceed the device limit of ${e} bytes`,{needed:n,limit:e,path:t,algorithm:null})}function pl(n,e,t){return new S("E_INVALID_ARGUMENT",`${n}: expected ${t}`,{argument:n,value:e,expected:t})}function HS(n){return gl(Math.floor(n.maxStorageBufferBindingSize/4))}function KS(n,e,t){if(n.length===0)throw pl("rowPtr",n.length,"nodeCount + 1 entries");if(!Number.isInteger(t)||t<uo||t%uo!==0)throw pl("arcsPerWindow",t,`a positive multiple of ${uo}`);const r=n.length-1;if(n[r]!==e)throw pl("arcCount",e,`rowPtr[${r}] === ${n[r]}`);const o=[];if(e===0)return o;let s=0,i=0,a=0;for(;s<e;){for(;n[i+1]<=s;)i++;const c=gl(s),l=c+t;if(n[i+1]>l)o.push({start:c,end:l,rowFirst:a,rowLast:i,bufferIndex:0,offset:4*c}),s=l,a=i;else{let u=i;for(;u+1<r&&n[u+2]<=l;)u++;const d=n[u+1];o.push({start:c,end:d,rowFirst:a,rowLast:u,bufferIndex:0,offset:4*c}),s=d,a=u+1}}return o}function YS(n,e,t){if(e<=t)return{buffers:[{byteOffset:0,byteLength:e}],placed:[...n]};const r=[],o=[];let s=0;for(;s<n.length;){let i=s;for(;i+1<n.length&&4*(n[i+1].end-n[s].start)<=t;)i++;const a=n[s].start,c=r.length;r.push({byteOffset:4*a,byteLength:4*(n[i].end-a)});for(let l=s;l<=i;l++){const u=n[l];o.push({start:u.start,end:u.end,rowFirst:u.rowFirst,rowLast:u.rowLast,bufferIndex:c,offset:4*(u.start-a)})}s=i+1}return{buffers:r,placed:o}}function XS(n,e,t){const{limits:r}=e,o=r.maxStorageBufferBindingSize,s=r.maxBufferSize,i=p=>p<=o&&p<=s,a=p=>p>o?o:s,c=jS(n),l=qS(t,c);if(!i(c.rowPtr))throw wl(c.rowPtr,a(c.rowPtr),"rowPtr");const{arena:u}=n;if(u!==null){const m=l.some(v=>(v==="arcToEdge"||v==="edgeToArc")&&u.segments[v]!==null)&&u.byteLength<=s,y=m?u.byteLength:u.hotByteLength,b=l.every(v=>{const A=u.segments[v];return A===null||i(A.byteLength)});if(y<=s&&b){const v=A=>{const E=u.segments[A];if(E===null)return null;const I=E.byteOffset-u.byteOffset;return I+E.byteLength<=y?{offset:I,size:E.byteLength}:null};return{kind:"arena",bytes:y,includesCold:m,segments:{rowPtr:v("rowPtr"),colIdx:v("colIdx"),weights:v("weights"),arcToEdge:v("arcToEdge"),edgeToArc:v("edgeToArc")}}}}if(l.every(p=>i(c[p])))return{kind:"perArray",arrays:l.map(p=>({name:p,byteLength:c[p],buffers:[{byteOffset:0,byteLength:c[p]}]}))};if(l.includes("edgeToArc")&&!i(c.edgeToArc))throw wl(c.edgeToArc,a(c.edgeToArc),"binding");const d=Math.min(HS(r),gl(Math.floor(s/4)));if(d<uo)throw wl(4*uo,o,"binding");const f=KS(n.rowPtr,n.arcCount,d),{buffers:h,placed:g}=YS(f,4*n.arcCount,s);return{kind:"windowed",arrays:l.map(p=>VS.has(p)?{name:p,byteLength:c[p],buffers:h}:{name:p,byteLength:c[p],buffers:[{byteOffset:0,byteLength:c[p]}]}),windows:g,arcsPerWindow:d}}const QS=Object.freeze(["rowPtr","colIdx","weights"]),JS=Object.freeze(["rowPtr","colIdx","weights","arcToEdge","edgeToArc"]),ZS=Object.freeze(["colIdx","weights","arcToEdge"]),eP=Se.STORAGE|Se.COPY_DST|Se.COPY_SRC;function tP(n){return ZS.includes(n)}function nP(n){return Object.prototype.toString.call(n)==="[object SharedArrayBuffer]"}function rr(n,e,t){return new S("E_INVALID_ARGUMENT",`${n}: expected ${t}`,{argument:n,value:e,expected:t})}function Ni(n){if(n.detached)throw new S("E_SNAPSHOT",`snapshot ${n.serial} is detached (its core was transferred away)`,{reason:"detached",serial:n.serial})}function rP(n,e){switch(e){case"rowPtr":return!0;case"colIdx":return n.arcCount>0;case"weights":return n.flags.weighted&&n.arcCount>0;case"arcToEdge":return!n.flags.arcToEdgeIsIdentity&&n.arcCount>0;case"edgeToArc":return!n.flags.arcToEdgeIsIdentity&&n.edgeCount>0;default:return!1}}function sp(n,e){switch(e){case"rowPtr":return n.rowPtr;case"colIdx":return n.colIdx;case"weights":{const{weights:t}=n;if(t===null)throw rr("weights",null,"a weighted snapshot");return t}case"arcToEdge":return n.arcToEdge;case"edgeToArc":return n.edgeToArc;default:throw rr("name",e,"a core array name")}}class oP{constructor(e,t,r,o){this.residents=new WeakMap,this.records=new WeakMap,this.bySerial=new Map,this.orphans=new Set,this.tombstones=new Set,this.liveCount=0,this.liveBytesValue=0,this.warned=!1,this.disposed=!1,this.device=e,this.caps=t,this.allocator=r,this.warnUnreleasedSnapshots=o.warnUnreleasedSnapshots,this.warn=o.warn??(s=>{console.warn(s)})}core(e,t){this.assertLive(),Ni(e);const r=t??QS,o=JS.filter(l=>(l==="rowPtr"||r.includes(l))&&rP(e,l)),s=XS(e,this.caps,o),i=this.ensureRecord(e);if(i.plan===null&&(i.plan=s.kind,s.kind==="arena"&&e.arena!==null)){const{arena:l}=e,u=this.upload(i,e.rowPtr,new Uint8Array(l.buffer,l.byteOffset,s.bytes),`residency:core:${i.serial}:arena`);i.arena={buffer:u.buffer,segments:s.segments}}s.kind==="windowed"&&i.windows===null&&(i.plan="windowed",i.windows=s.windows),this.bindMissing(i,e,s,o);const a=i.bindings.get("rowPtr");if(a===void 0)throw rr("rowPtr",null,"a bound rowPtr (internal invariant)");const c=i.bindings.get("weights")??null;return Object.freeze({serial:i.serial,plan:s.kind,rowPtr:a,colIdx:i.bindings.get("colIdx")??null,weights:c,arcToEdge:i.bindings.get("arcToEdge")??null,edgeToArc:i.bindings.get("edgeToArc")??null,windows:i.windows,arcBuffers:i.windows===null?null:Object.freeze({colIdx:Object.freeze([...i.arcBuffers.get("colIdx")??[]]),weights:Object.freeze([...i.arcBuffers.get("weights")??[]]),arcToEdge:Object.freeze([...i.arcBuffers.get("arcToEdge")??[]])}),hasWeights:c!==null})}view(e,t,r){this.assertLive(),Ni(e);const o=r?.packViews===!0;if(t==="reverse"||t==="edgeList"){this.assertNotReleased(e),this.assertNonEmpty(e);const d=o?`${t}:packed`:t,f=this.ensureRecord(e),h=f.views.get(d);if(h!==void 0)return h;const g=t==="reverse"?this.buildReverse(e,f,o):this.buildEdgeList(e,f,o);return f.views.set(d,g),g}if(o)throw new S("E_UNSUPPORTED","packViews applies to the reverse and edgeList views only",{option:"packViews",hint:`the ${t} view uploads one array`});let s,i,a={};switch(t){case"outDegree":this.assertNotReleased(e),this.assertNonEmpty(e),s=e.outDegree(),i="outDegree";break;case"inDegree":this.assertNotReleased(e),this.assertNonEmpty(e),s=e.inDegree(),i="inDegree";break;case"degreeOrder":{this.assertNotReleased(e),this.assertNonEmpty(e);const d=e.degreeOrder();s=d.perm,i="perm",a={segmentOffsets:Array.from(d.segmentOffsets)};break}case"reverseDegreeOrder":{this.assertNotReleased(e),this.assertNonEmpty(e);const d=e.degreeOrder({of:"reverse"});s=d.perm,i="perm",a={segmentOffsets:Array.from(d.segmentOffsets)};break}case"coo":if(this.assertNotReleased(e),this.assertNonEmpty(e),e.arcCount===0)return Object.freeze({view:t,bindings:Object.freeze({}),scalars:Object.freeze({})});s=e.coo().src,i="src";break;case"mate":throw new S("E_UNSUPPORTED","the mate view is not uploaded: no kernel reads it",{feature:"view:mate",hint:"outDegree, inDegree, degreeOrder, reverseDegreeOrder, coo, reverse and edgeList are uploaded"});default:throw rr("name",t,"a view name")}const c=this.ensureRecord(e),l=this.upload(c,s,s,`residency:view:${c.serial}:${t}`),u={buffer:l.buffer,offset:0,size:l.byteLength,window:null};return Object.freeze({view:t,bindings:Object.freeze({[i]:u}),scalars:Object.freeze(a)})}buildReverse(e,t,r){const o=e.reverse();if(!e.directed){const a=this.core(e,["rowPtr","colIdx","weights"]);if(a.plan==="windowed")throw new S("E_TOO_LARGE",`snapshot ${e.serial}: the undirected reverse view is the core, which needs arc windows (${a.windows?.length??0}) that no view executes`,{needed:4*e.arcCount,limit:this.caps.limits.maxStorageBufferBindingSize,path:"windowed",algorithm:null});const c={rowPtr:a.rowPtr};return a.colIdx!==null&&(c.colIdx=a.colIdx),a.weights!==null&&(c.weights=a.weights),Object.freeze({view:"reverse",bindings:Object.freeze(c),scalars:Object.freeze({arcCount:[o.arcCount],directed:[0]})})}const s=[["rowPtr",o.rowPtr],["colIdx",o.colIdx]];o.weights!==null&&s.push(["weights",o.weights]);const i=r?this.packArrays(t,s,this.packKey(t,"reverse:packed"),`residency:view:${t.serial}:reverse:packed`):this.separateArrays(t,s,`residency:view:${t.serial}:reverse`);return Object.freeze({view:"reverse",bindings:i,scalars:Object.freeze({arcCount:[o.arcCount],directed:[1]})})}buildEdgeList(e,t,r){const o=e.edgeList(),s=[["src",o.src],["dst",o.dst]];o.weights!==null&&s.push(["weights",o.weights]);const i=r?this.packArrays(t,s,this.packKey(t,"edgeList:packed"),`residency:view:${t.serial}:edgeList:packed`):this.separateArrays(t,s,`residency:view:${t.serial}:edgeList`);return Object.freeze({view:"edgeList",bindings:i,scalars:Object.freeze({edgeCount:[e.edgeCount]})})}separateArrays(e,t,r){const o={};for(const[s,i]of t){if(i.byteLength===0)continue;const a=this.upload(e,i,i,`${r}:${s}`);o[s]={buffer:a.buffer,offset:0,size:a.byteLength,window:null}}return Object.freeze(o)}packArrays(e,t,r,o){const s=t.filter(([,d])=>d.byteLength>0);if(s.length===0)return Object.freeze({});const i=[];let a=0;for(const[,d]of s)i.push(a),a+=Math.ceil(d.byteLength/ki)*ki;const c=new Uint8Array(a);s.forEach(([,d],f)=>{c.set(new Uint8Array(d.buffer,d.byteOffset,d.byteLength),i[f])});const l=this.upload(e,r,c,o),u={};return s.forEach(([d,f],h)=>{u[d]={buffer:l.buffer,offset:i[h],size:f.byteLength,window:null}}),Object.freeze(u)}packKey(e,t){const r=e.packKeys.get(t);if(r!==void 0)return r;const o={};return e.packKeys.set(t,o),o}column(e,t,r){this.assertLive(),Ni(r),this.assertNotReleased(r);const o=e.require(t),s=e.gpuView(t);if(s.byteLength===0)throw rr("column",t,"a column with at least one row (zero-length arrays are never uploaded)");const i=this.ensureRecord(r),a=`residency:column:${i.serial}:${o.meta.domain}.${t}`,c=this.residents.get(o);let l;return c!==void 0&&!c.destroyed&&c.serial===i.serial&&c.byteLength===s.byteLength?(l=c,l.version!==o.version&&(this.device.queue.writeBuffer(l.buffer,0,s),l.version=o.version)):(c!==void 0&&this.residents.delete(o),l=this.upload(i,o,s,a),l.version=o.version),Object.freeze({binding:{buffer:l.buffer,offset:0,size:l.byteLength,window:null},column:o,version:l.version,eligibility:o.gpu,components:o.meta.components})}array(e,t,r){if(this.assertLive(),e.byteLength===0||e.byteLength%4!==0)throw rr("key",e.byteLength,"a non-empty array whose byteLength is a multiple of 4");if(nP(e.buffer))throw rr("key","SharedArrayBuffer","an array over a plain ArrayBuffer");let o=null;r!==void 0&&(Ni(r),this.assertNotReleased(r),o=this.ensureRecord(r));const s=this.upload(o,e,e,`residency:array:${t}`);return{binding:{buffer:s.buffer,offset:0,size:s.byteLength,window:null},byteLength:s.byteLength,owner:r??null,destroy:()=>{this.destroyResident(s,o)}}}release(e){const t=this.bySerial.get(e.serial);if(t!==void 0){for(const r of[...t.entries])this.destroyResident(r,t);this.forget(t),this.tombstones.add(e.serial)}}clearOnLoss(){for(const e of[...this.bySerial.values()]){for(const t of e.entries)t.destroyed=!0,this.residents.get(t.key)===t&&this.residents.delete(t.key);e.entries.length=0,this.forget(e)}for(const e of this.orphans)e.destroyed=!0,this.residents.get(e.key)===e&&this.residents.delete(e.key);this.orphans.clear(),this.liveCount=0,this.liveBytesValue=0}destroyAll(){for(const e of[...this.bySerial.values()]){for(const t of[...e.entries])this.destroyResident(t,e);this.forget(e)}for(const e of[...this.orphans])this.destroyResident(e,null);this.disposed=!0}stats(){const e=[...this.bySerial.values()].map(t=>({serial:t.serial,label:t.label,bytes:t.entries.reduce((r,o)=>r+o.byteLength,0),buffers:t.entries.length}));return{buffers:this.liveCount,bytes:this.liveBytesValue,snapshots:this.bySerial.size,perSnapshot:e}}get residentBytes(){return this.liveBytesValue}isReleased(e){return this.tombstones.has(e)}bindMissing(e,t,r,o){for(const s of o)if(!e.bindings.has(s)){const i=r.kind==="windowed"?r.arrays.find(a=>a.name===s):void 0;e.bindings.set(s,i!==void 0&&i.buffers.length>0&&e.windows!==null&&tP(s)?this.bindWindowed(e,t,s,i.buffers,e.windows[0]):this.bindCore(e,t,s))}}bindCore(e,t,r){if(e.arena!==null){const i=e.arena.segments[r];if(i!==null)return{buffer:e.arena.buffer,offset:i.offset,size:i.size,window:null}}const o=sp(t,r),s=this.upload(e,o,o,`residency:core:${e.serial}:${r}`);return{buffer:s.buffer,offset:0,size:s.byteLength,window:null}}bindWindowed(e,t,r,o,s){const i=sp(t,r),a=o.map((c,l)=>this.upload(e,this.windowKey(e,`${r}:${l}`),new Uint8Array(i.buffer,i.byteOffset+c.byteOffset,c.byteLength),`residency:core:${e.serial}:${r}:w${l}`).buffer);return e.arcBuffers.set(r,a),{buffer:a[s.bufferIndex],offset:s.offset,size:4*(s.end-s.start),window:s}}windowKey(e,t){const r=e.windowKeys.get(t);if(r!==void 0)return r;const o={};return e.windowKeys.set(t,o),o}upload(e,t,r,o){const s=e===null?null:e.serial,i=this.residents.get(t);if(i!==void 0&&!i.destroyed&&i.serial===s)return i;const a=this.allocator.createBuffer({label:o,size:r.byteLength,usage:eP});this.device.queue.writeBuffer(a,0,r);const c={key:t,buffer:a,byteLength:r.byteLength,serial:s,version:0,destroyed:!1};return this.residents.set(t,c),e===null?this.orphans.add(c):e.entries.push(c),this.liveCount++,this.liveBytesValue+=r.byteLength,c}destroyResident(e,t){if(!e.destroyed){if(e.destroyed=!0,this.allocator.destroy(e.buffer),this.residents.get(e.key)===e&&this.residents.delete(e.key),t===null)this.orphans.delete(e);else{const r=t.entries.indexOf(e);r>=0&&t.entries.splice(r,1)}this.liveCount--,this.liveBytesValue-=e.byteLength}}forget(e){e.released=!0,e.bindings.clear(),e.views.clear(),e.packKeys.clear(),e.windowKeys.clear(),e.arcBuffers.clear(),e.windows=null,e.arena=null,e.plan=null,this.bySerial.delete(e.serial)}ensureRecord(e){let t=this.records.get(e);return t?.released&&(t=void 0),t===void 0&&(t=this.bySerial.get(e.serial)),t===void 0&&(t={serial:e.serial,label:e.label,entries:[],plan:null,arena:null,bindings:new Map,views:new Map,packKeys:new Map,windowKeys:new Map,windows:null,arcBuffers:new Map,released:!1},this.bySerial.set(e.serial,t),this.tombstones.delete(e.serial),!this.warned&&this.bySerial.size>this.warnUnreleasedSnapshots&&(this.warned=!0,this.warn(`[webgpu-graph-algorithms] ${this.bySerial.size} snapshots are resident on the device (warnUnreleasedSnapshots = ${this.warnUnreleasedSnapshots}); call ctx.release(snapshot) for superseded snapshots -- GPU memory is never freed by garbage collection (spec 4.1)`))),this.records.set(e,t),t}assertNotReleased(e){if(this.tombstones.has(e.serial))throw new S("E_RELEASED",`snapshot ${e.serial} was released; upload it again through core() before binding views, columns or arrays`,{serial:e.serial})}assertNonEmpty(e){if(e.nodeCount===0)throw rr("snapshot",0,"nodeCount > 0 (an empty snapshot has no per-node view to upload)")}assertLive(){if(this.disposed)throw new S("E_DISPOSED","the residency was disposed",{label:"residency"})}}const sP="webgpu-graph-algorithms",iP=Object.freeze(["subgroups","timestamp-query"]),ip="high-performance";async function aP(n){if(n.adapter!==void 0)return n.adapter;if(n.gpu!==void 0)return Vw(n.gpu,n.powerPreference??ip);throw new S("E_NO_WEBGPU","GpuContext.create needs one of gpu, adapter or device",{reason:"no gpu, adapter or device given",hint:"pass navigator.gpu (browser) or the gpu of createNodeGpu() (Node), or use the ./browser and ./node entries"})}class po{constructor(e){this.currentState="ready",this.lostError=null,this.slot=new tS,this.lostListeners=new Set,this.disposers=[],this.batchCounter=0,this.device=e.device,this.caps=e.caps,this.ownsDevice=e.ownsDevice,this.label=e.label,this.debug={inspect:!1},this.workgroupSize=ll(e.caps),this.allocator=new eS(e.device),this.residency=new oP(e.device,e.caps,this.allocator,{warnUnreleasedSnapshots:e.warnUnreleasedSnapshots}),this.pool=new hl(e.device,this.allocator,e.caps.limits.maxBufferSize),this.readback=new GS(e.device,this.allocator),this.pipelines=new LS(e.device,e.caps),this.profiler=e.device.features.has("timestamp-query")?new MS(e.device,!0,e.caps.runtime!=="node"):null,this.uninstallSink=rS(e.device,this.slot,e.onError),this.lost=oS(e.device,t=>{this.handleLost(t)})}static async probe(e){const{gpu:t}=e;if(t===void 0)return{ok:!1,code:"E_NO_WEBGPU",reason:"no GPU object: navigator.gpu is undefined (no WebGPU in this runtime)",adapter:null,summary:null};let r;try{r=await Vw(t,e.powerPreference??ip)}catch(s){return{ok:!1,code:"E_NO_ADAPTER",reason:go(s)?s.message:String(s),adapter:null,summary:null}}const o=wo(r);return e.rejectSoftware===!0&&o.software?{ok:!1,code:"E_SOFTWARE_ONLY",reason:`software adapter rejected: ${o.vendor}/${o.architecture}`,adapter:r,summary:o}:{ok:!0,code:"OK",reason:null,adapter:r,summary:o}}static async create(e){const t=e.runtime??"unknown",r=e.label??sP,o=e.onError??null,s=e.warnUnreleasedSnapshots??xw;if(e.device!==void 0){const f=qw(e.device,{runtime:t});return ul(f),new po({device:e.device,caps:f,ownsDevice:!1,label:r,onError:o,warnUnreleasedSnapshots:s})}const i=await aP(e),a=wo(i);if(e.rejectSoftware===!0&&a.software)throw new S("E_SOFTWARE_ONLY",`software adapter rejected by rejectSoftware: ${a.vendor}/${a.architecture}`,{adapter:a});const c=Yk(i,e.limits??"raise"),l=Xk(i,e.requiredFeatures??[],e.optionalFeatures??iP),u=await Qk(i,{label:r,requiredLimits:c,requiredFeatures:l}),d=Jk(u,i.info,t,e.gpu?.wgslLanguageFeatures??[]);try{ul(d)}catch(f){throw u.destroy(),f}return new po({device:u,caps:d,ownsDevice:!0,label:r,onError:o,warnUnreleasedSnapshots:s})}static from(e,t){const r=qw(e,t);ul(r);const o=e.label??"";return new po({device:e,caps:r,ownsDevice:!1,label:o===""?"GpuContext.from":o,onError:null,warnUnreleasedSnapshots:xw})}get state(){return this.currentState}assertReady(){if(this.currentState==="disposed")throw new S("E_DISPOSED",`GpuContext "${this.label}" is disposed`,{label:this.label});if(this.lostError!==null)throw this.lostError;const e=this.slot.take();if(e!==null)throw e}takePendingError(){return this.slot.take()}nextBatchId(){return this.batchCounter+=1,this.batchCounter}onLost(e){return this.lostListeners.add(e),()=>{this.lostListeners.delete(e)}}attachDisposer(e){if(this.currentState==="disposed"){e();return}this.disposers.push(e)}release(e){this.currentState!=="disposed"&&(this.residency.release(e),this.pool.trim())}dispose(){if(this.currentState==="disposed")return;this.currentState="disposed",this.uninstallSink(),this.residency.destroyAll(),this.pool.destroyAll(),this.readback.destroyAll(),this.profiler!==null&&this.profiler.destroy(),this.ownsDevice&&this.device.destroy();const e=this.disposers.splice(0);for(const t of e)t()}handleLost(e){if(this.currentState!=="disposed"){this.currentState="lost",this.lostError=Hw(e),this.residency.clearOnLoss();for(const t of Array.from(this.lostListeners))try{t(e)}catch{}}}}const ap=2e3;async function cP(n,e){let t;const r=new Promise(o=>{t=setTimeout(o,e)});await Promise.race([n.then(()=>{},()=>{}),r]),clearTimeout(t)}function lP(n){return n instanceof Error?n.message:typeof n=="string"?n:`non-error thrown (${typeof n})`}class Pe{constructor(e,t,r){this.requests=[],this.openPass=null,this.dispatchCount=0,this.stagingBytes=0,this.slot=null,this.submitted=!1,this.host=e,this.id=e.nextBatchId(),this.generation=r??0,this.label=t,this.encoder=e.device.createCommandEncoder({label:`batch/${t}#${this.id}`})}get dispatches(){return this.dispatchCount}pass(e){this.assertOpen("pass"),this.endPass();const t={label:`batch/${this.label}#${this.id}/${e}`},r=this.host.profiler?.beginPass(e);r!==void 0&&(t.timestampWrites=r);const o=this.encoder.beginComputePass(t);return this.countDispatches(o),this.openPass=o,o}endPass(){this.openPass!==null&&(this.openPass.end(),this.openPass=null)}copy(e,t,r){if(this.assertOpen("copy"),this.checkByteLength(r),r>e.size||r>t.size)throw new S("E_INVALID_ARGUMENT",`copy of ${r} bytes exceeds a binding (src ${e.size}, dst ${t.size})`,{argument:"byteLength",value:r,expected:`<= ${Math.min(e.size,t.size)}`});this.endPass(),this.encoder.copyBufferToBuffer(e.buffer,e.offset,t.buffer,t.offset,r)}readback(e,t,r){if(this.assertOpen("readback"),this.checkByteLength(r),!Number.isInteger(t)||t<0||t%4!==0||t+r>e.size)throw new S("E_INVALID_ARGUMENT",`readback of [${t}, ${t+r}) is outside the ${e.size}-byte source or not 4-aligned`,{argument:"srcOffset",value:t,expected:`a multiple of 4 with srcOffset + byteLength <= ${e.size}`});const o={src:e,srcOffset:t,byteLength:r,offset:this.stagingBytes};return this.requests.push(o),this.stagingBytes+=r,this.ensureSlot(this.stagingBytes),o}resolveQuerySet(e,t,r,o){this.assertOpen("resolveQuerySet"),this.endPass(),this.encoder.resolveQuerySet(e,t,r,o,0)}submit(){this.assertOpen("submit"),this.submitted=!0,this.endPass();const{slot:e}=this,t=this.host.takePendingError();try{this.host.assertReady()}catch(c){throw this.releaseSlot(),c}if(e!==null)for(const c of this.requests)this.encoder.copyBufferToBuffer(c.src,c.srcOffset,e.buffer,c.offset,c.byteLength);const r=this.encoder.finish({label:`batch/${this.label}#${this.id}`});this.host.device.queue.submit([r]);const o=this.host.takePendingError(),s=t??o,i={discarded:!1},a=s===null?this.awaitReadback(e,i):this.rejectReadback(s);return{id:this.id,generation:this.generation,readback:a,discard:()=>{i.discarded=!0}}}rejectReadback(e){return this.releaseSlot(),Promise.reject(this.attribute(e))}async awaitReadback(e,t){if(e===null)return await this.host.allocator.check(),new ArrayBuffer(0);const r=this.stagingBytes;let o=()=>{};const s=new Promise((c,l)=>{o=this.host.onLost(u=>{l(Hw(u))})});s.catch(()=>{});const i=this.host.readback.mapSlot(e,r);i.catch(()=>{});let a;try{await Promise.race([i,s]),this.host.assertReady(),a=t.discarded?new ArrayBuffer(0):e.buffer.getMappedRange(0,r).slice(0)}catch(c){throw await cP(i,ap),this.releaseSlot(),await this.classify(c,s)}finally{o()}return this.releaseSlot(),await this.host.allocator.check(),a}async classify(e,t){if(go(e))return e.code==="E_DEVICE_LOST"||e.code==="E_DISPOSED"?e:this.attribute(e);try{this.host.assertReady()}catch(a){if(go(a))return a.code==="E_DEVICE_LOST"||a.code==="E_DISPOSED"?a:this.attribute(a)}let r;const o=new Promise(a=>{r=setTimeout(()=>{a(null)},ap)}),s=await Promise.race([t.then(()=>null,a=>a),o]);if(clearTimeout(r),go(s))return s;const i=lP(e);return new S("E_VALIDATION",`mapAsync failed for batch ${this.id} "${this.label}": ${i}`,{label:this.label,message:i,batchId:this.id})}attribute(e){return new S(e.code,`${e.message} (delivered to batch ${this.id} "${this.label}")`,{...e.details,batchId:this.id,batchLabel:this.label})}ensureSlot(e){this.slot!==null&&this.slot.capacity>=e||(this.releaseSlot(),this.slot=this.host.readback.borrowSlot(e))}releaseSlot(){if(this.slot===null)return;const{slot:e}=this;this.slot=null;try{this.host.readback.returnSlot(e)}catch(t){if(!go(t)||t.code!=="E_DISPOSED")throw t}}countDispatches(e){const t=e.dispatchWorkgroups.bind(e),r=e.dispatchWorkgroupsIndirect.bind(e);e.dispatchWorkgroups=(o,s,i)=>{this.dispatchCount+=1,t(o,s,i)},e.dispatchWorkgroupsIndirect=(o,s)=>{this.dispatchCount+=1,r(o,s)}}assertOpen(e){if(this.submitted)throw new S("E_INVALID_ARGUMENT",`${e}() after submit() on batch ${this.id} "${this.label}"`,{argument:e,value:this.id,expected:"a batch that has not been submitted"})}checkByteLength(e){if(!Number.isInteger(e)||e<=0||e%4!==0)throw new S("E_INVALID_ARGUMENT",`byteLength ${e} is not a positive multiple of 4`,{argument:"byteLength",value:e,expected:"a positive multiple of 4"})}}function cp(n){return Math.min(lo,n.limits.maxComputeWorkgroupsPerDimension)}function ml(n,e){if(!Number.isInteger(e)||e<0)throw new S("E_INVALID_ARGUMENT",`${n} must be a non-negative integer, got ${e}`,{argument:n,value:e,expected:"a non-negative integer"})}function lp(n){let e=n;for(;Number.isInteger(e)&&e>1&&e%2===0;)e/=2;if(e!==1)throw new S("E_INVALID_ARGUMENT",`wg must be a power of two, got ${n}`,{argument:"wg",value:n,expected:"a power of two >= 1"})}function up(n,e,t){const r=cp(t);if(n===0)return{x:0,y:1,z:1,items:e,stride:null};if(n<=r)return{x:n,y:1,z:1,items:e,stride:null};const o=Math.ceil(n/r);if(o>r)throw new S("E_TOO_LARGE",`${n} workgroups exceed the 2D dispatch limit of ${r*r}`,{needed:n,limit:r*r,path:"dispatch",algorithm:null,items:e});return{x:r,y:o,z:1,items:e,stride:null}}function se(n,e,t){return ml("items",n),lp(e),up(Math.ceil(n/e),n,t)}function mo(n,e){return ml("groups",n),up(n,n,e)}function gt(n,e,t,r){if(ml("items",n),lp(e),n===0)return{x:0,y:1,z:1,items:n,stride:null};const o=Math.min(r??(t.software?64:4096),cp(t)),s=Math.min(Math.ceil(n/e),o);return{x:s,y:1,z:1,items:n,stride:s*e}}function yl(n){return n.x*n.y}const dp=Object.freeze({u32:{size:4,align:4,width:1,scalar:"u32"},i32:{size:4,align:4,width:1,scalar:"i32"},f32:{size:4,align:4,width:1,scalar:"f32"},vec2f:{size:8,align:8,width:2,scalar:"f32"},vec2u:{size:8,align:8,width:2,scalar:"u32"},vec4f:{size:16,align:16,width:4,scalar:"f32"},vec4u:{size:16,align:16,width:4,scalar:"u32"}}),bl=16,uP=/^[A-Za-z_]\w*$/,dP=4294967295,fP=-2147483648,hP=2147483647;function fp(n,e){return Math.ceil(n/e)*e}function hp(n,e){if(!uP.test(e)||Zw.includes(e))throw new S("E_INVALID_ARGUMENT",`UniformBlock: "${e}" is not a usable WGSL identifier`,{argument:n,value:e,expected:"a WGSL identifier that is not a reserved word"})}function gp(n,e,t){if(typeof t!="number")throw new S("E_INVALID_ARGUMENT",`UniformBlock: field "${n}" expects a number`,{argument:n,value:t,expected:e});if(e==="u32"&&!(Number.isInteger(t)&&t>=0&&t<=dP))throw new S("E_INVALID_ARGUMENT",`UniformBlock: field "${n}" is not a u32`,{argument:n,value:t,expected:"an integer in [0, 4294967295]"});if(e==="i32"&&!(Number.isInteger(t)&&t>=fP&&t<=hP))throw new S("E_INVALID_ARGUMENT",`UniformBlock: field "${n}" is not an i32`,{argument:n,value:t,expected:"an integer in [-2147483648, 2147483647]"})}function gP(n,e,t,r){e==="u32"?n.setUint32(t,r,!0):e==="i32"?n.setInt32(t,r,!0):n.setFloat32(t,r,!0)}function wp(n,e,t){return e==="u32"?n.getUint32(t,!0):e==="i32"?n.getInt32(t,!0):n.getFloat32(t,!0)}class Ie{static define(e,t,r){if(hp("name",e),t.length===0)throw new S("E_INVALID_ARGUMENT",`UniformBlock ${e}: a block needs at least one field`,{argument:"fields",value:t.length,expected:">= 1 field"});const o=[],s=new Map;let i=0;for(const[f,h]of t){if(hp("fields",f),s.has(f))throw new S("E_INVALID_ARGUMENT",`UniformBlock ${e}: duplicate field "${f}"`,{argument:"fields",value:f,expected:"unique field names"});const g=dp[h];if(g===void 0)throw new S("E_INVALID_ARGUMENT",`UniformBlock ${e}: unknown field type "${h}"`,{argument:"fields",value:h,expected:Object.keys(dp).join(" | ")});const w=fp(i,g.align),p={name:f,type:h,offset:w,info:g};o.push(p),s.set(f,p),i=w+g.size}const a=fp(i,bl),c=r?.padTo;if(c!==void 0&&(!Number.isInteger(c)||c%bl!==0||c<a))throw new S("E_INVALID_ARGUMENT",`UniformBlock ${e}: padTo ${c} is not a multiple of 16 >= ${a}`,{argument:"padTo",value:c,expected:`a multiple of ${bl} not below ${a}`});const l=c??a,u=o.map((f,h)=>{const g=h===o.length-1,w=f.offset+f.info.size;return` ${g&&w<l?`@size(${l-f.offset}) `:""}${f.name}: ${f.type},`}),d=`struct ${e} {
222
+ ${u.join(`
223
+ `)}
224
+ }`;return new Ie(e,r?.layout??"uniform",t,l,d,o,s)}constructor(e,t,r,o,s,i,a){this.name=e,this.layout=t,this.fields=Object.freeze(r.map(([c,l])=>Object.freeze([c,l]))),this.byteLength=o,this.wgsl=s,this.laidOut=i,this.table=a}offsetOf(e){return this.fieldLayout(e).offset}write(e,t,r){const o=this.regionStart(e,r);for(const i of Object.keys(t))if(!this.table.has(i))throw new S("E_INVALID_ARGUMENT",`UniformBlock ${this.name}: unknown field "${i}"`,{argument:"values",value:i,expected:this.laidOut.map(a=>a.name).join(", ")});const s=this.laidOut.map(i=>this.components(i,t[i.name]));for(let i=0;i<this.byteLength;i+=4)e.setUint32(o+i,0,!0);this.laidOut.forEach((i,a)=>{const c=s[a];c!==null&&c.forEach((l,u)=>{gP(e,i.info.scalar,o+i.offset+4*u,l)})})}components(e,t){if(t===void 0)return null;const{scalar:r,width:o}=e.info;if(o===1)return gp(e.name,r,t),[t];if(!Array.isArray(t)||t.length!==o)throw new S("E_INVALID_ARGUMENT",`UniformBlock ${this.name}: field "${e.name}" expects ${o} components`,{argument:e.name,value:t,expected:`an array of ${o} numbers`});const s=[];for(let i=0;i<o;i++){const a=t[i];gp(e.name,r,a),s.push(a)}return s}read(e,t){const r=this.regionStart(e,t),o={};for(const s of this.laidOut)o[s.name]=this.decode(e,s,r);return o}readField(e,t,r){const o=this.fieldLayout(t);return this.decode(e,o,this.regionStart(e,r))}fieldLayout(e){const t=this.table.get(e);if(t===void 0)throw new S("E_INVALID_ARGUMENT",`UniformBlock ${this.name}: unknown field "${e}"`,{argument:"field",value:e,expected:this.laidOut.map(r=>r.name).join(", ")});return t}regionStart(e,t){const r=t??0;if(!Number.isInteger(r)||r<0||r+this.byteLength>e.byteLength)throw new S("E_INVALID_ARGUMENT",`UniformBlock ${this.name}: region [${r}, ${r+this.byteLength}) is outside the view`,{argument:"byteOffset",value:r,expected:`0 <= byteOffset <= ${e.byteLength-this.byteLength}`});return r}decode(e,t,r){const{scalar:o,width:s}=t.info;if(s===1)return wp(e,o,r+t.offset);const i=[];for(let a=0;a<s;a++)i.push(wp(e,o,r+t.offset+4*a));return i}}const wP=`
225
+ var<workgroup> sh: array<u32, WG>; // the block's degrees, then their inclusive scan
226
+ var<workgroup> rowStart: array<u32, WG>; // the first bound arc of each entry's row
227
+ var<workgroup> base: u32; // the block's reserved span in the edge queue
228
+ var<workgroup> wcount: u32; // the frontier's length on a two-phase level, 0 on any other
229
+
230
+ @compute @workgroup_size(WG)
231
+ fn advance_expand(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
232
+ if (lid.x == 0u) { wcount = select(0u, atomicLoad(&counters[0]), atomicLoad(&counters[24]) == 1u); } // frontierCount, on the two-phase path only (the path word)
233
+ let count = workgroupUniformLoad(&wcount); // uniform: the block loop below holds barriers
234
+ for (var b0 = group_id(wid) * WG; b0 < count; b0 = b0 + P.stride) { // grid-stride over blocks of WG entries (a direct dispatch of the plan's groups)
235
+ let i = b0 + lid.x; // this lane's frontier entry
236
+ var deg = 0u;
237
+ var start = 0u;
238
+ if (i < count) { // guarded loads into locals (3.5 rule 1)
239
+ let v = frontierIn[i];
240
+ let lo = max(rowPtr[v], P.arcBase); // the row clipped to the bound window (P8-T12)
241
+ let hi = min(rowPtr[v + 1u], P.arcEnd);
242
+ start = lo;
243
+ deg = select(0u, hi - lo, hi > lo);
244
+ }
245
+ let inclusive = wg_scan_u32(deg, lid.x); // the prelude's inclusive scan in LANE order (P8-T1 Step 5); the twin
246
+ sh[lid.x] = inclusive; // sh is monotone in lid.x, the index the binary search walks
247
+ rowStart[lid.x] = start;
248
+ workgroupBarrier();
249
+ let aggregate = workgroupUniformLoad(&sh[WG - 1u]); // uniform; includes a barrier
250
+ if (lid.x == 0u) {
251
+ base = atomicAdd(&counters[8], aggregate); // edgeCount: ONE reservation per workgroup, not one per arc
252
+ atomicAdd(&counters[9], aggregate); // edgeCountUnclamped: the overflow detector (PD-23)
253
+ atomicAdd(&counters[2], aggregate); // frontierDegreeSum: what this level expanded (the inspect seam)
254
+ }
255
+ workgroupBarrier();
256
+ for (var p = lid.x; p < aggregate; p = p + WG) { // strip [0, aggregate): lane j takes j, j + WG, ...
257
+ var lo = 0u; // upper_bound: the first k with sh[k] > p owns arc p
258
+ var hi = WG;
259
+ loop {
260
+ if (lo >= hi) { break; }
261
+ let mid = (lo + hi) / 2u;
262
+ if (sh[mid] > p) { hi = mid; } else { lo = mid + 1u; }
263
+ }
264
+ let k = lo;
265
+ var exclusive = 0u;
266
+ if (k > 0u) { exclusive = sh[k - 1u]; }
267
+ let arc = rowStart[k] + (p - exclusive);
268
+ let q = base + p;
269
+ if (q < P.edgeCapacity) { edgeQueue[q] = colIdx[arc - P.arcBase]; } // the clamp of PD-23; the queue holds the target vertex only (PD-24)
270
+ }
271
+ workgroupBarrier(); // sh, rowStart and base are reused by the next block
272
+ }
273
+ }
274
+ `,pP=`
275
+ var<workgroup> tileA: array<f32, APSP_TILE * APSP_TILE>;
276
+ var<workgroup> tileB: array<f32, APSP_TILE * APSP_TILE>;
277
+
278
+ fn tile_row(block: vec2<u32>, c: u32) -> u32 { return block.x * APSP_TILE + c / APSP_TILE; }
279
+ fn tile_col(block: vec2<u32>, c: u32) -> u32 { return block.y * APSP_TILE + c % APSP_TILE; }
280
+
281
+ fn load_cell(block: vec2<u32>, c: u32) -> f32 {
282
+ let i = tile_row(block, c);
283
+ let j = tile_col(block, c);
284
+ if (i < P.n && j < P.n) { return dist[i * P.n + j]; }
285
+ return bitcast<f32>(P.infBits); // outside the matrix: no path through it
286
+ }
287
+
288
+ fn store_cell(block: vec2<u32>, c: u32, v: f32) {
289
+ let i = tile_row(block, c);
290
+ let j = tile_col(block, c);
291
+ if (i >= P.n || j >= P.n) { return; } // an edge tile stores nothing outside n x n
292
+ dist[i * P.n + j] = v;
293
+ }
294
+
295
+ @compute @workgroup_size(WG)
296
+ fn apsp_fw(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
297
+ let g = group_id(wid);
298
+ let r = P.round;
299
+ let others = max(P.blocks, 2u) - 1u; // the blocks of a strip, the pivot excluded
300
+ let cells = APSP_TILE * APSP_TILE;
301
+ var count = 1u;
302
+ var own = vec2<u32>(r, r); // the block this workgroup updates
303
+ var a = vec2<u32>(r, r); // staged in tileA
304
+ var b = vec2<u32>(r, r); // staged in tileB
305
+ if (PHASE == 1u) {
306
+ count = 2u * others;
307
+ let s = g % others;
308
+ let o = select(s, s + 1u, s >= r); // a strip skips the pivot block
309
+ own = select(vec2<u32>(o, r), vec2<u32>(r, o), g < others); // block row r first, then block column r
310
+ b = own;
311
+ }
312
+ if (PHASE == 2u) {
313
+ count = others * others;
314
+ let i = g / others;
315
+ let j = g % others;
316
+ own = vec2<u32>(select(i, i + 1u, i >= r), select(j, j + 1u, j >= r));
317
+ a = vec2<u32>(own.x, r); // the pivot-column block (i, r)
318
+ b = vec2<u32>(r, own.y); // the pivot-row block (r, j)
319
+ }
320
+ if (g >= count) { return; } // uniform: the workgroup id and uniforms only
321
+
322
+ for (var c = lid.x; c < cells; c = c + WG) {
323
+ tileA[c] = load_cell(a, c);
324
+ if (PHASE != 0u) { tileB[c] = load_cell(b, c); }
325
+ }
326
+ workgroupBarrier(); // every staged cell is visible
327
+
328
+ if (PHASE == 2u) {
329
+ for (var c = lid.x; c < cells; c = c + WG) {
330
+ let x = c / APSP_TILE;
331
+ let y = c % APSP_TILE;
332
+ var v = load_cell(own, c);
333
+ for (var kr = 0u; kr < APSP_TILE; kr = kr + 1u) {
334
+ v = min(v, tileA[x * APSP_TILE + kr] + tileB[kr * APSP_TILE + y]);
335
+ }
336
+ store_cell(own, c, v);
337
+ }
338
+ return;
339
+ }
340
+
341
+ let pivotRow = PHASE == 1u && own.x == r; // block row r reads d[x][k] from the pivot
342
+ for (var k = 0u; k < APSP_TILE; k = k + 1u) {
343
+ for (var c = lid.x; c < cells; c = c + WG) {
344
+ let x = c / APSP_TILE;
345
+ let y = c % APSP_TILE;
346
+ if (PHASE == 0u) {
347
+ let via = tileA[x * APSP_TILE + k] + tileA[k * APSP_TILE + y];
348
+ if (via < tileA[c]) { tileA[c] = via; }
349
+ } else {
350
+ let left = select(tileB[x * APSP_TILE + k], tileA[x * APSP_TILE + k], pivotRow);
351
+ let right = select(tileA[k * APSP_TILE + y], tileB[k * APSP_TILE + y], pivotRow);
352
+ let via = left + right;
353
+ if (via < tileB[c]) { tileB[c] = via; }
354
+ }
355
+ }
356
+ workgroupBarrier(); // step k is complete before step k + 1 reads
357
+ }
358
+ for (var c = lid.x; c < cells; c = c + WG) {
359
+ store_cell(own, c, select(tileB[c], tileA[c], PHASE == 0u));
360
+ }
361
+ }
362
+ `,mP=`
363
+ @compute @workgroup_size(WG)
364
+ fn apsp_init(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
365
+ let u = linear_id(wid, lid.x);
366
+ if (u >= P.n) { return; }
367
+ let rowBase = u * P.n;
368
+ let end = rowPtr[u + 1u];
369
+ for (var a = rowPtr[u]; a < end; a = a + 1u) {
370
+ let v = colIdx[a];
371
+ let w = select(1.0, weights[a], HAS_WEIGHTS);
372
+ dist[rowBase + v] = min(dist[rowBase + v], w); // parallel arcs collapse to the cheapest
373
+ }
374
+ dist[rowBase + u] = 0.0; // last: a self-loop never displaces the zero
375
+ }
376
+ `,yP=`
377
+ fn sigma_of(word: u32) -> f32 { // a stored count: u32, or f32 bits when SCALED
378
+ if (SCALED) { return bitcast<f32>(word); }
379
+ return f32(word);
380
+ }
381
+
382
+ @compute @workgroup_size(WG)
383
+ fn bc_backward(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
384
+ for (var i = linear_id(wid, lid.x); i < P.count; i = i + P.stride) {
385
+ let t = S[P.start + i]; // s * n + w
386
+ let w = t % P.n;
387
+ let base = t - w; // s * n
388
+ let succ = depthK[t] + 1u;
389
+ let sw = sigma_of(sigmaK[t]);
390
+ let shift = select(0i, sigma_shift(levelMax[depthK[t]]), SCALED); // the scale step to the successors' depth
391
+ var acc = 0.0;
392
+ for (var a = rowPtr[w]; a < rowPtr[w + 1u]; a = a + 1u) {
393
+ let v = base + colIdx[a];
394
+ if (depthK[v] == succ) { // v is a successor of w for source s
395
+ acc = acc + ldexp(sw / sigma_of(sigmaK[v]), -shift) * (1.0 + deltaK[v]);
396
+ }
397
+ }
398
+ deltaK[t] = acc; // written once per (w, s)
399
+ }
400
+ }
401
+ `,bP=`
402
+ @compute @workgroup_size(WG)
403
+ fn bc_count(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
404
+ let level = atomicLoad(&counters[11]);
405
+ let start = ends[level + 1u]; // the boundary closed the claim-from level here
406
+ let count = atomicLoad(&counters[26]) - start; // stackTop: what the forward dispatch appended
407
+ let shift = sigma_shift(atomicLoad(&levelMax[level]));
408
+ for (var i = linear_id(wid, lid.x); i < count; i = i + P.stride) {
409
+ let t = S[start + i]; // s * n + x, at depth level + 1
410
+ let x = t % P.n;
411
+ let base = t - x; // s * n
412
+ var acc = 0.0;
413
+ for (var a = rowPtr[x]; a < rowPtr[x + 1u]; a = a + 1u) { // the in-arcs (v, x)
414
+ let v = base + colIdx[a];
415
+ if (depthK[v] == level) { acc = acc + bitcast<f32>(sigmaK[v]); } // every predecessor's paths, CSR order
416
+ }
417
+ let sigma = ldexp(acc, -shift);
418
+ let bits = bitcast<u32>(sigma);
419
+ sigmaK[t] = bits;
420
+ let exponent = (bits >> 23u) & 0xffu;
421
+ if (exponent == 0u || exponent == 0xffu) { atomicOr(&counters[27], 1u); } // out of f32's normal range
422
+ atomicMax(&levelMax[level + 1u], bits);
423
+ }
424
+ }
425
+ `,vP=`
426
+ fn sigma_of(word: u32) -> f32 { // a stored count: u32, or f32 bits when SCALED
427
+ if (SCALED) { return bitcast<f32>(word); }
428
+ return f32(word);
429
+ }
430
+
431
+ @compute @workgroup_size(WG)
432
+ fn bc_edge_gather(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
433
+ for (var a = linear_id(wid, lid.x); a < P.count; a = a + P.stride) {
434
+ var lo = 0u; // the row w with rowPtr[w] <= a < rowPtr[w + 1]
435
+ var hi = P.n;
436
+ loop {
437
+ if (lo >= hi) { break; }
438
+ let mid = (lo + hi) / 2u;
439
+ if (rowPtr[mid + 1u] <= a) { lo = mid + 1u; } else { hi = mid; }
440
+ }
441
+ let w = lo;
442
+ let nbr = colIdx[a];
443
+ var acc = arcScores[a];
444
+ for (var s = 0u; s < P.k; s = s + 1u) {
445
+ let base = s * P.n;
446
+ let dw = depthK[base + w];
447
+ if (dw != INVALID_INDEX && depthK[base + nbr] == dw + 1u) { // (w, nbr) is on a shortest path from s
448
+ let shift = select(0i, sigma_shift(levelMax[dw]), SCALED);
449
+ let ratio = ldexp(sigma_of(sigmaK[base + w]) / sigma_of(sigmaK[base + nbr]), -shift);
450
+ acc = acc + ratio * (1.0 + deltaK[base + nbr]);
451
+ }
452
+ }
453
+ arcScores[a] = acc;
454
+ }
455
+ }
456
+ `,AP=`
457
+ @compute @workgroup_size(WG)
458
+ fn bc_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
459
+ if (lid.x != 0u) { return; } // one lane; no barrier follows (3.5 rule 1)
460
+ if (P.role == 1u) { // the seed of a batch
461
+ for (var i = 0u; i < P.k; i = i + 1u) {
462
+ let t = S[i];
463
+ depthK[t] = 0u; // the source is at depth 0
464
+ sigmaK[t] = select(1u, bitcast<u32>(1.0), SCALED); // with one shortest path, itself (f32 bits when SCALED)
465
+ }
466
+ levelMax[0] = bitcast<u32>(1.0); // the largest count at depth 0
467
+ ends[0] = 0u;
468
+ atomicStore(&counters[26], P.k); // stackTop: the seeds are the log's first k entries
469
+ atomicStore(&counters[27], 0u); // sigmaOverflow
470
+ atomicStore(&counters[11], U32_MAX); // level: the first boundary brings it to 0
471
+ atomicStore(&counters[15], 0u); // done
472
+ return;
473
+ }
474
+ if (atomicLoad(&counters[15]) != 0u) { return; } // done: a no-op level the host recorded past the end
475
+ let level = atomicLoad(&counters[11]) + 1u;
476
+ let top = atomicLoad(&counters[26]);
477
+ ends[level + 1u] = top; // the level's entries end where the log ends now
478
+ let count = top - ends[level];
479
+ atomicStore(&counters[0], count); // frontierCount (the inspect seam reads it)
480
+ atomicStore(&counters[11], level);
481
+ atomicStore(&counters[15], select(0u, 1u, count == 0u)); // an empty level ends the batch
482
+ }
483
+ `,EP=`
484
+ var<workgroup> sh: array<u32, WG>; // the block's degrees, then their inclusive scan
485
+ var<workgroup> rowStart: array<u32, WG>; // the first arc of each entry's row
486
+ var<workgroup> entryOf: array<u32, WG>; // each entry, s * n + u
487
+ var<workgroup> wstart: u32; // the level's first log index
488
+ var<workgroup> wcount: u32; // the level's entry count
489
+ var<workgroup> wwon: atomic<u32>; // the strip's winners
490
+ var<workgroup> wbase: u32; // where the strip's winners go in the log
491
+
492
+ @compute @workgroup_size(WG)
493
+ fn bc_forward(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
494
+ let level = atomicLoad(&counters[11]);
495
+ if (lid.x == 0u) {
496
+ let lo = ends[level];
497
+ wstart = lo;
498
+ wcount = ends[level + 1u] - lo;
499
+ }
500
+ let start = workgroupUniformLoad(&wstart);
501
+ let count = workgroupUniformLoad(&wcount); // uniform: the block loop below holds barriers
502
+ let next = level + 1u;
503
+ for (var b0 = group_id(wid) * WG; b0 < count; b0 = b0 + P.stride) { // grid-stride over blocks of WG entries
504
+ let i = b0 + lid.x;
505
+ var deg = 0u;
506
+ var first = 0u;
507
+ var entry = 0u;
508
+ if (i < count) { // guarded loads into locals (3.5 rule 1)
509
+ entry = S[start + i];
510
+ let u = entry % P.n;
511
+ first = rowPtr[u];
512
+ deg = rowPtr[u + 1u] - first;
513
+ }
514
+ sh[lid.x] = deg;
515
+ rowStart[lid.x] = first;
516
+ entryOf[lid.x] = entry;
517
+ workgroupBarrier();
518
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan of the degrees
519
+ var t = 0u;
520
+ if (lid.x >= s) { t = sh[lid.x - s]; }
521
+ workgroupBarrier();
522
+ sh[lid.x] = sh[lid.x] + t;
523
+ workgroupBarrier();
524
+ }
525
+ let aggregate = workgroupUniformLoad(&sh[WG - 1u]); // uniform; includes a barrier
526
+ for (var p0 = 0u; p0 < aggregate; p0 = p0 + WG) { // strip [0, aggregate) WG arcs at a time
527
+ let p = p0 + lid.x;
528
+ var won = false;
529
+ var claimed = 0u;
530
+ if (p < aggregate) {
531
+ var lo = 0u; // upper_bound: the first k with sh[k] > p owns arc p
532
+ var hi = WG;
533
+ loop {
534
+ if (lo >= hi) { break; }
535
+ let mid = (lo + hi) / 2u;
536
+ if (sh[mid] > p) { hi = mid; } else { lo = mid + 1u; }
537
+ }
538
+ let k = lo;
539
+ var exclusive = 0u;
540
+ if (k > 0u) { exclusive = sh[k - 1u]; }
541
+ let origin = entryOf[k]; // s * n + u
542
+ let x = (origin - (origin % P.n)) + colIdx[rowStart[k] + (p - exclusive)]; // s * n + x
543
+ if (atomicLoad(&depthK[x]) == INVALID_INDEX) { // the pre-check of design 16.1
544
+ won = atomicMin(&depthK[x], next) == INVALID_INDEX; // the claim: the one winner appends
545
+ }
546
+ if (!SCALED && atomicLoad(&depthK[x]) == next) { // the count: EVERY arc on a shortest path adds
547
+ let add = atomicLoad(&sigmaK[origin]);
548
+ let old = atomicAdd(&sigmaK[x], add);
549
+ if (old + add < old) { atomicOr(&counters[27], 1u); } // the u32 wrap, reported
550
+ }
551
+ claimed = x;
552
+ }
553
+ var slot = 0u;
554
+ if (won) { slot = atomicAdd(&wwon, 1u); }
555
+ workgroupBarrier();
556
+ if (lid.x == 0u) {
557
+ wbase = atomicAdd(&counters[26], atomicLoad(&wwon)); // stackTop: one global atomic per strip
558
+ atomicStore(&wwon, 0u);
559
+ }
560
+ workgroupBarrier();
561
+ if (won) { S[wbase + slot] = claimed; }
562
+ }
563
+ workgroupBarrier(); // sh, rowStart and entryOf are reused by the next block
564
+ }
565
+ }
566
+ `,_P=`
567
+ var<workgroup> wlive: u32; // 1 when the level has entries
568
+ var<workgroup> wwon: atomic<u32>; // the strip's winners
569
+ var<workgroup> wbase: u32; // where the strip's winners go in the log
570
+
571
+ fn claim(x: u32, next: u32) -> bool {
572
+ if (atomicLoad(&depthK[x]) != INVALID_INDEX) { return false; } // the pre-check of design 16.1
573
+ return atomicMin(&depthK[x], next) == INVALID_INDEX;
574
+ }
575
+
576
+ fn count_paths(origin: u32, x: u32, next: u32) {
577
+ if (!SCALED && atomicLoad(&depthK[x]) == next) { // every arc on a shortest path adds
578
+ let add = atomicLoad(&sigmaK[origin]);
579
+ let old = atomicAdd(&sigmaK[x], add);
580
+ if (old + add < old) { atomicOr(&counters[27], 1u); } // the u32 wrap, reported
581
+ }
582
+ }
583
+
584
+ @compute @workgroup_size(WG)
585
+ fn bc_forward_edge(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
586
+ let level = atomicLoad(&counters[11]);
587
+ if (lid.x == 0u) { wlive = select(0u, 1u, ends[level + 1u] > ends[level]); }
588
+ if (workgroupUniformLoad(&wlive) == 0u) { return; } // uniform: nothing below runs on an empty level
589
+ let next = level + 1u;
590
+ for (var s = 0u; s < P.k; s = s + 1u) {
591
+ let base = s * P.n;
592
+ for (var e0 = group_id(wid) * WG; e0 < P.count; e0 = e0 + P.stride) { // grid-stride over the edges
593
+ let e = e0 + lid.x;
594
+ var a = INVALID_INDEX; // the claims this lane won
595
+ var b = INVALID_INDEX;
596
+ if (e < P.count) {
597
+ let u = base + edgeSrc[e];
598
+ let x = base + edgeDst[e];
599
+ if (atomicLoad(&depthK[u]) == level) {
600
+ if (claim(x, next)) { a = x; }
601
+ count_paths(u, x, next);
602
+ }
603
+ if (UNDIRECTED) { // the other direction of an undirected edge
604
+ if (atomicLoad(&depthK[x]) == level) {
605
+ if (claim(u, next)) { b = u; }
606
+ count_paths(x, u, next);
607
+ }
608
+ }
609
+ }
610
+ let mine = select(0u, 1u, a != INVALID_INDEX) + select(0u, 1u, b != INVALID_INDEX);
611
+ var slot = 0u;
612
+ if (mine != 0u) { slot = atomicAdd(&wwon, mine); }
613
+ workgroupBarrier();
614
+ if (lid.x == 0u) {
615
+ wbase = atomicAdd(&counters[26], atomicLoad(&wwon)); // stackTop: one global atomic per strip
616
+ atomicStore(&wwon, 0u);
617
+ }
618
+ workgroupBarrier();
619
+ if (a != INVALID_INDEX) {
620
+ S[wbase + slot] = a;
621
+ slot = slot + 1u;
622
+ }
623
+ if (b != INVALID_INDEX) { S[wbase + slot] = b; }
624
+ }
625
+ }
626
+ }
627
+ `,IP=`
628
+ @compute @workgroup_size(WG)
629
+ fn bc_gather(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
630
+ for (var w = linear_id(wid, lid.x); w < P.n; w = w + P.stride) {
631
+ var acc = bc[w];
632
+ for (var s = 0u; s < P.k; s = s + 1u) {
633
+ acc = acc + deltaK[s * P.n + w];
634
+ }
635
+ bc[w] = acc;
636
+ }
637
+ }
638
+ `,kP=`
639
+ fn relax(v: u32, nd: f32) {
640
+ var cur = atomicLoad(&dist[v]);
641
+ var tries = 0u;
642
+ loop {
643
+ if (!(nd < bitcast<f32>(cur))) { break; } // no improvement; +Inf is greater than every finite nd
644
+ let r = atomicCompareExchangeWeak(&dist[v], cur, bitcast<u32>(nd));
645
+ if (r.exchanged) { atomicStore(&flags[0], 1u); break; } // changed
646
+ if (r.old_value == cur) { // a spurious failure: the only kind the bound counts
647
+ tries = tries + 1u;
648
+ if (tries >= P.maxRetries) { atomicStore(&flags[1], 1u); break; } // retryExhausted (PD-12)
649
+ }
650
+ cur = r.old_value; // else another lane's improvement won (issue #470)
651
+ }
652
+ }
653
+
654
+ @compute @workgroup_size(WG)
655
+ fn bf_relax(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
656
+ let first = linear_id(wid, lid.x);
657
+ let cutoff = bitcast<f32>(P.cutoffBits);
658
+ for (var e = first; e < P.edgeCount; e = e + P.stride) { // each logical edge once (edgeList)
659
+ let u = edgeSrc[e];
660
+ let v = edgeDst[e];
661
+ let w = weights[edgeToArc[e]]; // the edge's weight through its forward arc
662
+ let du = atomicLoad(&dist[u]);
663
+ if (du != F32_INF_BITS) { // unreached is tested as the bit pattern, as sssp-pred does
664
+ let nd = bitcast<f32>(du) + w;
665
+ if (nd <= cutoff) { relax(v, nd); }
666
+ }
667
+ if (UNDIRECTED) { // the other direction of an undirected edge
668
+ let dv = atomicLoad(&dist[v]);
669
+ if (dv != F32_INF_BITS) {
670
+ let nd = bitcast<f32>(dv) + w;
671
+ if (nd <= cutoff) { relax(u, nd); }
672
+ }
673
+ }
674
+ }
675
+ }
676
+ `,SP=`
677
+ @compute @workgroup_size(WG)
678
+ fn bfs_bitset_build(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
679
+ let count = select(0u, atomicLoad(&counters[0]), atomicLoad(&counters[24]) == 3u); // frontierCount, on the bottom-up path only (the path word)
680
+ for (var i = linear_id(wid, lid.x); i < count; i = i + P.stride) { // grid-stride; no barrier anywhere
681
+ let v = frontierIn[i];
682
+ atomicOr(&bits[P.bitsBase + (v >> 5u)], 1u << (v & 31u));
683
+ }
684
+ }
685
+ `,PP=`
686
+ var<workgroup> sh: array<u32, WG>;
687
+ var<workgroup> base: u32;
688
+ var<workgroup> wcount: u32; // the unvisited list's length on a bottom-up level, 0 on any other
689
+
690
+ @compute @workgroup_size(WG)
691
+ fn bfs_bottom_up(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
692
+ let claim = atomicLoad(&counters[11]) + 1u;
693
+ if (lid.x == 0u) { wcount = select(0u, atomicLoad(&counters[7]), atomicLoad(&counters[24]) == 3u); } // unvisitedListLen, on the bottom-up path only (the path word)
694
+ let len = workgroupUniformLoad(&wcount); // uniform: the block loop below holds barriers
695
+ for (var b0 = group_id(wid) * WG; b0 < len; b0 = b0 + P.stride) { // grid-stride over blocks of WG entries
696
+ let i = b0 + lid.x;
697
+ var won = 0u;
698
+ var v = 0u;
699
+ var reads = 0u;
700
+ if (i < len) { // guarded work into locals
701
+ v = sweepIn[i];
702
+ if (atomicLoad(&depth[v]) == INVALID_INDEX) { // a stale entry, claimed since the rebuild, is skipped
703
+ let end = min(rowPtr[v + 1u], P.arcEnd);
704
+ for (var a = max(rowPtr[v], P.arcBase); a < end; a = a + 1u) { // in-neighbours through the reverse core
705
+ reads = reads + 1u;
706
+ let u = colIdx[a - P.arcBase];
707
+ if (mask_bit(sweepIn[P.bitsBase + (u >> 5u)], u)) { won = 1u; break; } // the early exit: a real break, never a flag
708
+ }
709
+ }
710
+ }
711
+ sh[lid.x] = won;
712
+ workgroupBarrier();
713
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan of won (bfs-contract's)
714
+ var t = 0u;
715
+ if (lid.x >= s) { t = sh[lid.x - s]; }
716
+ workgroupBarrier();
717
+ sh[lid.x] = sh[lid.x] + t;
718
+ workgroupBarrier();
719
+ }
720
+ let inclusive = sh[lid.x];
721
+ let readsTotal = wg_reduce_u32(reads, lid.x, 0u); // arcsScanned, one atomic per workgroup (the sabotage witness, Step 6)
722
+ if (lid.x == WG - 1u) { base = atomicAdd(&counters[1], inclusive); }
723
+ if (lid.x == 0u) { atomicAdd(&counters[16], readsTotal); }
724
+ workgroupBarrier();
725
+ if (won == 1u) {
726
+ atomicStore(&depth[v], claim); // no claim race: the list holds v once and the sweep is vertex-parallel
727
+ frontierOut[base + inclusive - 1u] = v;
728
+ }
729
+ workgroupBarrier(); // sh and base are reused by the next block
730
+ }
731
+ }
732
+ `,xP=`
733
+ var<workgroup> sh: array<u32, WG>;
734
+ var<workgroup> base: u32;
735
+ var<workgroup> wcount: u32; // the clamped edge count on a two-phase level, 0 on any other
736
+
737
+ @compute @workgroup_size(WG)
738
+ fn bfs_contract(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
739
+ if (lid.x == 0u) { wcount = select(0u, atomicLoad(&counters[8]), atomicLoad(&counters[24]) == 1u); } // edgeCount, clamped by role 1; the two-phase path only (the path word)
740
+ let count = workgroupUniformLoad(&wcount); // uniform: the block loop below holds barriers
741
+ let claim = atomicLoad(&counters[11]) + 1u; // the depth this level assigns
742
+ for (var b0 = group_id(wid) * WG; b0 < count; b0 = b0 + P.stride) { // grid-stride over blocks of WG entries
743
+ let i = b0 + lid.x;
744
+ var won = 0u;
745
+ var v = 0u;
746
+ if (i < count) { // guarded work into locals
747
+ v = edgeQueue[i];
748
+ let old = atomicMin(&depth[v], claim);
749
+ won = select(0u, 1u, old == INVALID_INDEX); // PD-6: the unique winner
750
+ }
751
+ sh[lid.x] = won;
752
+ workgroupBarrier();
753
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan of won
754
+ var t = 0u;
755
+ if (lid.x >= s) { t = sh[lid.x - s]; }
756
+ workgroupBarrier();
757
+ sh[lid.x] = sh[lid.x] + t;
758
+ workgroupBarrier();
759
+ }
760
+ let inclusive = sh[lid.x];
761
+ if (lid.x == WG - 1u) { base = atomicAdd(&counters[1], inclusive); } // nextFrontierCount: one reservation per workgroup
762
+ workgroupBarrier();
763
+ if (won == 1u) { frontierOut[base + inclusive - 1u] = v; }
764
+ workgroupBarrier(); // sh and base are reused by the next block
765
+ }
766
+ }
767
+ `,CP=`
768
+ var<workgroup> sh: array<u32, WG>;
769
+ var<workgroup> wdeg: u32;
770
+ var<workgroup> wstart: u32;
771
+ var<workgroup> base: u32;
772
+ var<workgroup> wcount: u32; // the frontier's length on a fused or retry level, 0 on any other
773
+
774
+ @compute @workgroup_size(WG)
775
+ fn bfs_fused(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
776
+ let claim = atomicLoad(&counters[11]) + 1u;
777
+ if (lid.x == 0u) {
778
+ let path = atomicLoad(&counters[24]); // 2 the fused level, 4 the overflow retry (PD-23)
779
+ wcount = select(0u, atomicLoad(&counters[0]), path == 2u || path == 4u);
780
+ }
781
+ let count = workgroupUniformLoad(&wcount); // uniform: the entry loop below holds barriers
782
+ for (var g = group_id(wid); g < count; g = g + P.stride) { // one workgroup per frontier entry; P.stride is the dispatch's GROUP count
783
+ if (lid.x == 0u) {
784
+ let u = frontierIn[g];
785
+ let a0 = max(rowPtr[u], P.arcBase);
786
+ let a1 = min(rowPtr[u + 1u], P.arcEnd);
787
+ let d = select(0u, a1 - a0, a1 > a0);
788
+ wdeg = d;
789
+ wstart = a0;
790
+ atomicAdd(&counters[2], d); // frontierDegreeSum, so the inspect seam sees fused levels too
791
+ }
792
+ let deg = workgroupUniformLoad(&wdeg); // uniform: the loop below may hold barriers
793
+ let start = workgroupUniformLoad(&wstart);
794
+ for (var p0 = 0u; p0 < deg; p0 = p0 + WG) { // strip the row WG arcs at a time
795
+ let p = p0 + lid.x;
796
+ var won = 0u;
797
+ var v = 0u;
798
+ if (p < deg) { // guarded claim into locals
799
+ v = colIdx[start + p - P.arcBase];
800
+ let old = atomicMin(&depth[v], claim);
801
+ won = select(0u, 1u, old == INVALID_INDEX);
802
+ }
803
+ sh[lid.x] = won;
804
+ workgroupBarrier();
805
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan of won (bfs-contract's, verbatim)
806
+ var t = 0u;
807
+ if (lid.x >= s) { t = sh[lid.x - s]; }
808
+ workgroupBarrier();
809
+ sh[lid.x] = sh[lid.x] + t;
810
+ workgroupBarrier();
811
+ }
812
+ let inclusive = sh[lid.x];
813
+ if (lid.x == WG - 1u) { base = atomicAdd(&counters[1], inclusive); }
814
+ workgroupBarrier();
815
+ if (won == 1u) { frontierOut[base + inclusive - 1u] = v; }
816
+ workgroupBarrier(); // sh and base are reused by the next strip
817
+ }
818
+ }
819
+ }
820
+ `,NP=`
821
+ @compute @workgroup_size(WG)
822
+ fn bfs_next_degree(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
823
+ let count = select(0u, atomicLoad(&counters[1]), atomicLoad(&counters[24]) != 0u); // nextFrontierCount, on a level that claimed (the path word)
824
+ var sum = 0u;
825
+ var inSum = 0u;
826
+ for (var i = linear_id(wid, lid.x); i < count; i = i + P.stride) { // no barrier inside: the trip count is per lane
827
+ let v = frontier[i];
828
+ sum = sum + outDegree[v];
829
+ inSum = inSum + inDegree[v];
830
+ }
831
+ let total = wg_reduce_u32(sum, lid.x, 0u); // the prelude's workgroup sum; uniform: after the loop
832
+ let inTotal = wg_reduce_u32(inSum, lid.x, 0u);
833
+ if (lid.x == 0u) {
834
+ atomicAdd(&counters[25], total); // nextDegreeSum: ONE atomic per workgroup
835
+ atomicSub(&counters[6], inTotal); // unvisitedDegreeSum: the claimed vertices' in-arcs leave it (issue #1358)
836
+ }
837
+ }
838
+ `,TP=`
839
+ @compute @workgroup_size(WG)
840
+ fn bfs_unvisited_flags(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
841
+ let first = linear_id(wid, lid.x);
842
+ var cnt = 0u;
843
+ var degSum = 0u;
844
+ var len = 0u;
845
+ for (var v = first; v < P.n; v = v + P.stride) { // no barrier inside: the trip count is per lane
846
+ let unv = depth[v] == INVALID_INDEX;
847
+ let listed = unv && (inDegree[v] != 0u);
848
+ flags[v] = select(0u, 1u, listed);
849
+ cnt = cnt + select(0u, 1u, unv);
850
+ degSum = degSum + select(0u, inDegree[v], unv); // the IN-degree: what a bottom-up sweep reads at most (issue #1358)
851
+ len = len + select(0u, 1u, listed);
852
+ }
853
+ let c = wg_reduce_u32(cnt, lid.x, 0u); // the prelude's workgroup sum (combine_u's sum code); uniform: after the loop
854
+ let d = wg_reduce_u32(degSum, lid.x, 0u);
855
+ let l = wg_reduce_u32(len, lid.x, 0u);
856
+ if (lid.x == 0u) { // ONE atomic per word per workgroup
857
+ atomicAdd(&counters[5], c);
858
+ atomicAdd(&counters[6], d);
859
+ atomicAdd(&counters[7], l);
860
+ }
861
+ }
862
+ `,OP=`
863
+ const max_words: u32 = 8u;
864
+ var<workgroup> tally: array<atomic<u32>, 32u * max_words>; // 32 x max_words: this workgroup's claims per source lane
865
+ var<workgroup> wlive: u32;
866
+ var<workgroup> wpull: u32;
867
+ var<workgroup> wany: atomic<u32>;
868
+ var<workgroup> warcs: atomic<u32>;
869
+ var<workgroup> wover: atomic<u32>;
870
+
871
+ fn dead_lanes(j: u32) -> u32 { // the lanes of word j at or past the batch's source count
872
+ let first = 32u * j;
873
+ if (P.count >= first + 32u) { return 0u; }
874
+ if (P.count <= first) { return U32_MAX; }
875
+ return ~((1u << (P.count - first)) - 1u);
876
+ }
877
+
878
+ fn add_arcs(slot: u32, value: u32) { // the arcs total of a control slot; pull once it passes P.pullAt
879
+ if (value == 0u) { return; }
880
+ let before = atomicAdd(&table[slot + 1u], value);
881
+ if (value > P.pullAt || before + value > P.pullAt || before + value < before) {
882
+ atomicStore(&table[slot + 2u], 1u);
883
+ }
884
+ }
885
+
886
+ fn record(j: u32, node: u32, fresh: u32, dist: u32) { // the claims of one word: tallied per lane, a sampled run's sums
887
+ if (P.perNode == 1u) { atomicAdd(&bits[4u * P.base + node], countOneBits(fresh) * dist); }
888
+ var b = fresh;
889
+ loop {
890
+ if (b == 0u) { break; }
891
+ atomicAdd(&tally[32u * j + firstTrailingBit(b)], 1u);
892
+ b = b & (b - 1u);
893
+ }
894
+ }
895
+
896
+ @compute @workgroup_size(WG)
897
+ fn closeness_level(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
898
+ let i = linear_id(wid, lid.x);
899
+ let W = P.words;
900
+ if (P.role == 1u) { // seed, part 1: one invocation per word
901
+ if (i == 0u) {
902
+ for (var k = 0u; k < 12u; k = k + 1u) { atomicStore(&table[P.ctrl + k], 0u); }
903
+ }
904
+ if (i < P.total) { atomicStore(&bits[i], select(0u, dead_lanes(i % W), i < P.base)); }
905
+ return; // uniform: P.role is
906
+ }
907
+ if (P.role == 2u) { // seed, part 2: one invocation per source lane
908
+ if (i < P.count) {
909
+ var v = P.source + i;
910
+ if (P.sourcesAt != 0u) { v = atomicLoad(&table[P.sourcesAt + P.source + i]); }
911
+ let w = v * W + i / 32u;
912
+ let bit = 1u << (i % 32u);
913
+ atomicOr(&bits[w], bit); // visited
914
+ let before = atomicOr(&bits[P.base + w], bit); // level 0's frontier (region 1)
915
+ let slot = P.ctrl + 8u; // the slot of "level -1", which level 0 reads
916
+ atomicStore(&table[slot], 1u);
917
+ if (before == 0u) { add_arcs(slot, rowPtr[v + 1u] - rowPtr[v]); }
918
+ }
919
+ return;
920
+ }
921
+
922
+ // role 0: one level
923
+ let L = P.level;
924
+ let prev = P.ctrl + 4u * ((L + 2u) % 3u);
925
+ let cur = P.ctrl + 4u * (L % 3u);
926
+ if (lid.x == 0u) {
927
+ wlive = atomicLoad(&table[prev]);
928
+ wpull = select(0u, atomicLoad(&table[prev + 2u]), P.pullOk == 1u);
929
+ atomicStore(&wany, 0u);
930
+ atomicStore(&warcs, 0u);
931
+ atomicStore(&wover, 0u);
932
+ }
933
+ for (var k = lid.x; k < 32u * W; k = k + WG) { atomicStore(&tally[k], 0u); }
934
+ let live = workgroupUniformLoad(&wlive); // uniform; includes a barrier
935
+ if (live == 0u) { return; } // the previous level claimed nothing
936
+ let pull = workgroupUniformLoad(&wpull) == 1u;
937
+ if (i == 0u) { // the slot of level L + 1 held level L - 2's
938
+ let nxt = P.ctrl + 4u * ((L + 1u) % 3u);
939
+ atomicStore(&table[nxt], 0u);
940
+ atomicStore(&table[nxt + 1u], 0u);
941
+ atomicStore(&table[nxt + 2u], 0u);
942
+ }
943
+ let frontierBase = P.base * (1u + L % 3u);
944
+ let nextBase = P.base * (1u + (L + 1u) % 3u);
945
+ let staleBase = P.base * (1u + (L + 2u) % 3u);
946
+ let dist = L + 1u;
947
+ var arcs = 0u;
948
+ if (i < P.n) {
949
+ for (var j = 0u; j < W; j = j + 1u) { atomicStore(&bits[staleBase + i * W + j], 0u); }
950
+ }
951
+ if (pull) {
952
+ if (i < P.n) { // one invocation per node: its in-arcs
953
+ var vis: array<u32, max_words>;
954
+ var unseen = 0u;
955
+ for (var j = 0u; j < W; j = j + 1u) {
956
+ vis[j] = atomicLoad(&bits[i * W + j]);
957
+ unseen = unseen | ~vis[j];
958
+ }
959
+ if (unseen != 0u) { // some source has not reached this node yet
960
+ var acc: array<u32, max_words>;
961
+ let end = inRowPtr[i + 1u];
962
+ for (var a = inRowPtr[i]; a < end; a = a + 1u) {
963
+ let u = inColIdx[a];
964
+ var missing = 0u;
965
+ for (var j = 0u; j < W; j = j + 1u) {
966
+ acc[j] = acc[j] | atomicLoad(&bits[frontierBase + u * W + j]);
967
+ missing = missing | ~(acc[j] | vis[j]);
968
+ }
969
+ if (missing == 0u) { break; } // every source has reached it: the early exit
970
+ }
971
+ let degree = rowPtr[i + 1u] - rowPtr[i];
972
+ for (var j = 0u; j < W; j = j + 1u) {
973
+ let fresh = acc[j] & ~vis[j];
974
+ if (fresh != 0u) {
975
+ atomicStore(&bits[i * W + j], vis[j] | fresh);
976
+ atomicStore(&bits[nextBase + i * W + j], fresh);
977
+ arcs = arcs + degree;
978
+ record(j, i, fresh, dist);
979
+ }
980
+ }
981
+ }
982
+ }
983
+ } else if (i < P.arcCount) { // one invocation per arc: no row is walked whole
984
+ var lo = 0u; // the arc's source: the last row starting at or before it
985
+ var hi = P.n - 1u;
986
+ loop {
987
+ if (lo >= hi) { break; }
988
+ let mid = (lo + hi + 1u) / 2u;
989
+ if (rowPtr[mid] <= i) { lo = mid; } else { hi = mid - 1u; }
990
+ }
991
+ let u = lo;
992
+ let x = colIdx[i];
993
+ for (var j = 0u; j < W; j = j + 1u) {
994
+ let mask = atomicLoad(&bits[frontierBase + u * W + j]) & ~atomicLoad(&bits[x * W + j]); // at u, not yet at x
995
+ if (mask == 0u) { continue; }
996
+ let fresh = mask & ~atomicOr(&bits[x * W + j], mask); // the claims this invocation won
997
+ if (fresh == 0u) { continue; }
998
+ if (atomicOr(&bits[nextBase + x * W + j], fresh) == 0u) {
999
+ arcs = arcs + (rowPtr[x + 1u] - rowPtr[x]);
1000
+ }
1001
+ record(j, x, fresh, dist);
1002
+ }
1003
+ }
1004
+ if (arcs > P.pullAt) {
1005
+ atomicStore(&wover, 1u);
1006
+ } else if (arcs != 0u) {
1007
+ let before = atomicAdd(&warcs, arcs);
1008
+ if (before + arcs > P.pullAt || before + arcs < before) { atomicStore(&wover, 1u); }
1009
+ }
1010
+ workgroupBarrier();
1011
+ let row = P.row * 32u * W;
1012
+ for (var k = lid.x; k < 32u * W; k = k + WG) { // ONE global atomic per source lane per workgroup
1013
+ let c = atomicLoad(&tally[k]);
1014
+ if (c != 0u) {
1015
+ atomicAdd(&table[row + k], c);
1016
+ atomicStore(&wany, 1u);
1017
+ }
1018
+ }
1019
+ workgroupBarrier();
1020
+ if (lid.x == 0u) {
1021
+ if (atomicLoad(&wany) != 0u) { atomicStore(&table[cur], 1u); }
1022
+ if (atomicLoad(&wover) != 0u) {
1023
+ atomicStore(&table[cur + 2u], 1u);
1024
+ } else {
1025
+ add_arcs(cur, atomicLoad(&warcs));
1026
+ }
1027
+ }
1028
+ }
1029
+ `,$P=`
1030
+ var<workgroup> partial: array<u32, WG>;
1031
+
1032
+ @compute @workgroup_size(WG)
1033
+ fn closeness_rowsum(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1034
+ let row = group_id(wid); // uniform: one workgroup per row
1035
+ if (row >= P.n) { return; }
1036
+ var whole = 0u;
1037
+ var real = 0.0;
1038
+ for (var c = lid.x; c < P.n; c = c + WG) {
1039
+ let d = dist[row * P.n + c];
1040
+ if (c == row || bitcast<u32>(d) == F32_INF_BITS) { continue; }
1041
+ if (P.role == 0u) {
1042
+ whole = whole + u32(d);
1043
+ } else if (P.role == 1u) {
1044
+ real = real + d;
1045
+ } else if (d > 0.0) {
1046
+ real = real + 1.0 / d; // a zero distance adds nothing, as on the CPU
1047
+ }
1048
+ }
1049
+ partial[lid.x] = select(whole, bitcast<u32>(real), P.role != 0u);
1050
+ for (var s = WG / 2u; s > 0u; s = s / 2u) {
1051
+ workgroupBarrier();
1052
+ if (lid.x < s) {
1053
+ let a = partial[lid.x];
1054
+ let b = partial[lid.x + s];
1055
+ partial[lid.x] = select(a + b, bitcast<u32>(bitcast<f32>(a) + bitcast<f32>(b)), P.role != 0u);
1056
+ }
1057
+ }
1058
+ if (lid.x == 0u) { out[row] = partial[0]; }
1059
+ }
1060
+ `,RP=`
1061
+ @compute @workgroup_size(WG)
1062
+ fn compact_scatter(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1063
+ let i = linear_id(wid, lid.x);
1064
+ if (i == 0u) { outCount[P.outIndex] = offsets[P.count - 1u] + flags[P.count - 1u]; } // the exclusive scan's total; the planner never dispatches for count 0
1065
+ if (i >= P.count) { return; } // no barrier follows
1066
+ if (flags[i] != 0u) { out[offsets[i]] = queue[i]; }
1067
+ }
1068
+ `,DP=`
1069
+ @compute @workgroup_size(WG)
1070
+ fn coo_emit(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1071
+ let i = linear_id(wid, lid.x);
1072
+ if (i >= P.count) { return; } // no barrier follows
1073
+ var a = i;
1074
+ if (INDEXED) { a = order[i]; } // the arc this position takes
1075
+ let e = a / 2u; // arc 2e is edge e as declared, arc 2e + 1 its reverse
1076
+ let forward = (a % 2u) == 0u;
1077
+ let u = edgeSrc[e];
1078
+ let v = edgeDst[e];
1079
+ var w = 1.0;
1080
+ if (WEIGHTED) { w = edgeWeight[e]; }
1081
+ if (u == v) { // a self-loop is dropped: both arcs sort last and never open a run
1082
+ outSrc[i] = INVALID_INDEX;
1083
+ outDst[i] = INVALID_INDEX;
1084
+ outWeight[i] = 0.0;
1085
+ return;
1086
+ }
1087
+ outSrc[i] = select(v, u, forward);
1088
+ outDst[i] = select(u, v, forward);
1089
+ outWeight[i] = w;
1090
+ }
1091
+ `,LP=`
1092
+ @compute @workgroup_size(WG)
1093
+ fn coo_scatter(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1094
+ let i = linear_id(wid, lid.x);
1095
+ if (i >= P.count) { return; } // no barrier follows
1096
+ let s = src[i];
1097
+ var slot = 0u;
1098
+ if (SORTED_INPUT) {
1099
+ if (i > 0u && s < src[i - 1u]) { atomicStore(&cursors[0], 1u); } // unsorted input: the flag the driver refuses
1100
+ let within = i - rowPtr[s]; // the arc's place in its row
1101
+ slot = rowPtr[s] + within;
1102
+ } else {
1103
+ slot = rowPtr[s] + atomicAdd(&cursors[s], 1u); // race order: the row is not sorted in this mode
1104
+ }
1105
+ colIdx[slot] = dst[i];
1106
+ if (WEIGHTED) { outWeight[slot] = weight[i]; }
1107
+ }
1108
+ `,MP=`
1109
+ @compute @workgroup_size(WG)
1110
+ fn counting_scatter(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1111
+ let i = linear_id(wid, lid.x);
1112
+ if (i >= P.count) { return; } // no barrier follows
1113
+ let k = keys[i];
1114
+ let slot = atomicAdd(&cursor[k], 1u); // the per-bin cursor (6 row 5)
1115
+ outIndex[start[k] + slot] = i;
1116
+ }
1117
+ `,UP=`
1118
+ @compute @workgroup_size(WG)
1119
+ fn dedupe_claim(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1120
+ var count = P.count;
1121
+ if (P.countIndex != U32_MAX) { count = min(atomicLoad(&counters[P.countIndex]), P.count); } // a device-side count, clamped to the capacity
1122
+ for (var i = linear_id(wid, lid.x); i < count; i = i + P.stride) { // grid-stride; no barrier anywhere
1123
+ atomicStore(&owner[queue[i]], i);
1124
+ }
1125
+ }
1126
+ `,FP=`
1127
+ var<workgroup> sh: array<u32, WG>;
1128
+ var<workgroup> base: u32;
1129
+ var<workgroup> wcount: u32;
1130
+
1131
+ @compute @workgroup_size(WG)
1132
+ fn dedupe_filter(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1133
+ if (lid.x == 0u) {
1134
+ var count = P.count;
1135
+ if (P.countIndex != U32_MAX) { count = min(atomicLoad(&outCount[P.countIndex]), P.count); } // the same count source as the claim
1136
+ wcount = count;
1137
+ }
1138
+ let count = workgroupUniformLoad(&wcount); // uniform: the block loop below holds barriers
1139
+ for (var b0 = group_id(wid) * WG; b0 < count; b0 = b0 + P.stride) { // grid-stride over blocks of WG entries
1140
+ let i = b0 + lid.x;
1141
+ var keep = 0u;
1142
+ var v = 0u;
1143
+ if (i < count) { v = queue[i]; keep = select(0u, 1u, atomicLoad(&owner[v]) == i); } // guarded work into locals
1144
+ sh[lid.x] = keep;
1145
+ workgroupBarrier(); // every lane, unconditionally (3.5 rule 1)
1146
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan of keep
1147
+ var t = 0u;
1148
+ if (lid.x >= s) { t = sh[lid.x - s]; }
1149
+ workgroupBarrier();
1150
+ sh[lid.x] = sh[lid.x] + t;
1151
+ workgroupBarrier();
1152
+ }
1153
+ let inclusive = sh[lid.x];
1154
+ if (lid.x == WG - 1u) { base = atomicAdd(&outCount[P.outIndex], inclusive); } // ONE atomic per workgroup: the block's aggregate
1155
+ workgroupBarrier();
1156
+ if (keep == 1u) { out[base + inclusive - 1u] = v; }
1157
+ workgroupBarrier(); // sh and base are reused by the next block
1158
+ }
1159
+ }
1160
+ `,BP=`
1161
+ @compute @workgroup_size(WG)
1162
+ fn degree(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1163
+ let row = linear_id(wid, lid.x) + P.start;
1164
+ if (row >= P.end) { return; }
1165
+ let i = select(row, perm[row], USE_PERM);
1166
+ let a0 = max(rowPtr[i], P.arcBase);
1167
+ let a1 = min(rowPtr[i + 1u], P.arcEnd);
1168
+ var d = 0u;
1169
+ for (var arc = a0; arc < a1; arc = arc + 1u) {
1170
+ let nbr = colIdx[arc - P.arcBase]; // \`target\` is a WGSL reserved word (spec 16.2); never use it as an identifier
1171
+ d = d + select(0u, 1u, nbr < P.n);
1172
+ }
1173
+ out[i] = select(d, out[i] + d, P.accumulate == 1u);
1174
+ }
1175
+ `,zP=`fn store_force(i: u32, f: vec3f) {
1176
+ force[3u * i] = f.x;
1177
+ force[3u * i + 1u] = f.y;
1178
+ force[3u * i + 2u] = f.z;
1179
+ }
1180
+ fn load_force(i: u32) -> vec3f { return vec3f(force[3u * i], force[3u * i + 1u], force[3u * i + 2u]); }
1181
+ fn row_node(row: u32) -> u32 { return select(row, perm[row], USE_PERM); }
1182
+ fn row_force(i: u32, lane: u32, step: u32) -> vec3f { // the arcs of row i this lane walks inside the bound window [P.arcBase, P.arcEnd) (4.2)
1183
+ let pi = pos[i]; // xyz + mass in one load (D23)
1184
+ let a0 = max(rowPtr[i], P.arcBase);
1185
+ let a1 = min(rowPtr[i + 1u], P.arcEnd);
1186
+ var f = vec3f(0.0);
1187
+ for (var a = a0 + lane; a < a1; a = a + step) {
1188
+ let j = colIdx[a - P.arcBase];
1189
+ if (j == i) { continue; } // a self-loop exerts no force
1190
+ var w = 1.0;
1191
+ if (HAS_WEIGHTS) { w = weights[a - P.arcBase]; }
1192
+ let d = pos[j].xyz - pi.xyz; // toward j
1193
+ let len = max(length(d), FA2_DIST_FLOOR);
1194
+ if (LAW == 1u) { w = length(d) / P.frK; } // LAW 1 (FR, 7.20): |F| = d^2 / k along d / d, unfloored; the linear select below applies w as is
1195
+ if (LAW == 2u) { w = P.springCoefficient * (len - P.springLength) / len; } // LAW 2 (spring, ngraph generateCreateSpringForce.js:33-36): Hooke k_s (d - L) toward j
1196
+ let mag = select(w, w * log(1.0 + len) / len, LINLOG); // linear: |F| = w len; linlog: |F| = w log(1 + len)
1197
+ f = f + d * mag;
1198
+ }
1199
+ return f;
1200
+ }
1201
+ fn row_force_dense(i: u32) -> vec3f { // TIER 0's stride-one twin of row_force (see the header)
1202
+ let pi = pos[i];
1203
+ let lo = max(rowPtr[i], P.arcBase);
1204
+ let hi = min(rowPtr[i + 1u], P.arcEnd);
1205
+ var total = vec3f(0.0);
1206
+ for (var left = select(0u, hi - lo, hi > lo); left > 0u; left = left - 1u) { // counts DOWN (see the header)
1207
+ let arc = hi - left; // lo, lo + 1, ..., hi - 1
1208
+ let k = arc - P.arcBase; // the window-local index; this walk is contiguous
1209
+ let nbr = colIdx[k];
1210
+ if (nbr == i) { continue; } // a self-loop exerts no force
1211
+ var weight = 1.0;
1212
+ if (HAS_WEIGHTS) { weight = weights[k]; }
1213
+ let d = pos[nbr].xyz - pi.xyz; // toward the neighbour
1214
+ let len = max(length(d), FA2_DIST_FLOOR);
1215
+ if (LAW == 1u) { weight = length(d) / P.frK; } // LAW 1 (FR, 7.20), as in row_force
1216
+ if (LAW == 2u) { weight = P.springCoefficient * (len - P.springLength) / len; } // LAW 2 (spring), as in row_force
1217
+ let mag = select(weight, weight * log(1.0 + len) / len, LINLOG);
1218
+ total = total + d * mag;
1219
+ }
1220
+ return total;
1221
+ }
1222
+ fn finish(i: u32, f0: vec3f) {
1223
+ var f = f0;
1224
+ if (DISTRIBUTED) { f = f / pos[i].w; }
1225
+ if (P.accumulate == 1u) { f = f + load_force(i); } // the windowed loop of 4.2 (arcBase != 0 dispatches after the first)
1226
+ store_force(i, f); // overwrites: attraction is the first writer of force each iteration
1227
+ }
1228
+ fn tier0(wid: vec3<u32>, lane: u32) { // TIER 0: one row per thread over [tierStart, tierEnd); no barrier, so the early return is legal (3.5 rule 1)
1229
+ let row = linear_id(wid, lane) + P.tierStart;
1230
+ if (row >= P.tierEnd) { return; }
1231
+ let i = row_node(row);
1232
+ finish(i, row_force_dense(i));
1233
+ }
1234
+
1235
+ var<workgroup> sh: array<vec3f, WG>;
1236
+
1237
+ fn tiered(wid: vec3<u32>, lid: u32) { // TIER 1: 32 lanes per row over [hiEnd, midEnd); TIER 2: WG lanes per row over [0, hiEnd) (PD-6, PD-7)
1238
+ let g = group_id(wid);
1239
+ var row = g;
1240
+ var end = P.hiEnd;
1241
+ var lane = lid;
1242
+ var step = WG;
1243
+ if (TIER == 1u) { row = P.hiEnd + g * (WG / 32u) + lid / 32u; end = P.midEnd; lane = lid % 32u; step = 32u; }
1244
+ let valid = row < end;
1245
+ var i = 0u;
1246
+ var f = vec3f(0.0);
1247
+ if (valid) { i = row_node(row); f = row_force(i, lane, step); }
1248
+ if (TIER == 1u) {
1249
+ sh[lid] = f;
1250
+ workgroupBarrier();
1251
+ for (var s = 16u; s >= 1u; s = s / 2u) { // the five-step tree over each 32-lane group; every lane runs every step
1252
+ var t = vec3f(0.0);
1253
+ if (lane < s) { t = sh[lid + s]; }
1254
+ workgroupBarrier();
1255
+ sh[lid] = sh[lid] + t;
1256
+ workgroupBarrier();
1257
+ }
1258
+ if (valid && lane == 0u) { finish(i, sh[lid]); }
1259
+ }
1260
+ if (TIER == 2u) {
1261
+ let t = wg_reduce_vec4(vec4f(f, 0.0), lid, 0u);
1262
+ if (valid && lid == 0u) { finish(i, t.xyz); }
1263
+ }
1264
+ }
1265
+
1266
+ @compute @workgroup_size(WG)
1267
+ fn attraction(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1268
+ if (TIER == 0u) { tier0(wid, lid.x); } else { tiered(wid, lid.x); }
1269
+ }`,GP=`fn load_force(i: u32) -> vec3f { return vec3f(force[3u * i], force[3u * i + 1u], force[3u * i + 2u]); }
1270
+ fn load_old(i: u32) -> vec3f { return vec3f(oldForce[3u * i], oldForce[3u * i + 1u], oldForce[3u * i + 2u]); }
1271
+ fn store_old(i: u32, f: vec3f) {
1272
+ oldForce[3u * i] = f.x;
1273
+ oldForce[3u * i + 1u] = f.y;
1274
+ oldForce[3u * i + 2u] = f.z;
1275
+ }
1276
+
1277
+ @compute @workgroup_size(WG)
1278
+ fn integrate(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1279
+ let i = linear_id(wid, lid.x);
1280
+ var dp = vec3f(0.0);
1281
+ var p = vec4f(0.0);
1282
+ var free = false;
1283
+ var valid = false;
1284
+ var ke = 0.0;
1285
+ if (i < P.n) {
1286
+ valid = true;
1287
+ let f = load_force(i);
1288
+ p = pos[i];
1289
+ var swing_i = p.w * length(f); // SWING_MODE 1: NetworkX's local swinging m |F| (layout.py line 1497)
1290
+ if (SWING_MODE == 0u) { swing_i = p.w * length(f - load_old(i)); } // paper: m |F(t) - F(t-1)|, recomputed inline (7.2)
1291
+ let factor = S.speed / (1.0 + sqrt(S.speed * swing_i));
1292
+ let fixed = mask_bit(fixedMask[i >> 5u], i);
1293
+ dp = select(f * factor, vec3f(0.0), fixed); // APPLY 0 (FA2): no clamp on dp (D25)
1294
+ if (APPLY == 1u) { // APPLY 1 (FR, 7.20): move along F by min(|F|, t); a fixed node stays
1295
+ let mag = length(f);
1296
+ let t = select(P.temperature, S.temperature, (P.flags & FA2_FLAG_ADAPTIVE) != 0u); // adaptive cooling: K1's state temperature
1297
+ dp = vec3f(0.0);
1298
+ if (mag > 0.0 && !fixed) { dp = f * (min(mag, t) / mag); }
1299
+ ke = select(0.0, dot(f, f), !fixed); // the force energy of Hu's step control, folded like the spring preset's kinetic energy
1300
+ }
1301
+ if (APPLY == 2u) { // APPLY 2 (spring-electrical): ngraph's Euler step over the velocity in the oldForce slot (PD-2)
1302
+ var v = load_old(i);
1303
+ let fd = f - P.dragCoefficient * v; // drag (generateCreateDragForce.js:18)
1304
+ v = v + (P.timeStep / p.w) * fd; // v += (dt / m) F (generateIntegrator.js:27-29)
1305
+ let sp = length(v);
1306
+ if (sp > 1.0) { v = v / sp; } // the unit speed clamp (generateIntegrator.js:33-37)
1307
+ if (P.dim == 2u) { v.z = 0.0; }
1308
+ dp = select(P.timeStep * v, vec3f(0.0), fixed); // dp = dt v; a pinned body is skipped (generateIntegrator.js:21, 39-41)
1309
+ if (!fixed) { store_old(i, v); }
1310
+ ke = select(0.0, 0.5 * p.w * dot(v, v), !fixed); // partials B under APPLY 2 (PD-4)
1311
+ }
1312
+ if (P.dim == 2u) { dp.z = 0.0; } // 2D never integrates z (7.13)
1313
+ p = vec4f(p.xyz + dp, p.w);
1314
+ pos[i] = p;
1315
+ if (SWING_MODE == 0u) { store_old(i, f); } // fixed nodes too, so a later unpin sees no stale swing (7.11)
1316
+ free = !fixed;
1317
+ }
1318
+ // uniform control flow from here (3.5 rule 1): partials A (sum p, sum |p - c|^2, min, max over valid rows) and C (sum |dp|, free count)
1319
+ let c = S.centroid.xyz;
1320
+ var sumv = vec4f(0.0);
1321
+ var lo = vec4f(F32_MAX);
1322
+ var hi = vec4f(-F32_MAX);
1323
+ var dl = 0.0;
1324
+ var fr = 0u;
1325
+ if (valid) {
1326
+ let q = p.xyz - c;
1327
+ sumv = vec4f(p.xyz, dot(q, q));
1328
+ lo = vec4f(p.xyz, 0.0);
1329
+ hi = vec4f(p.xyz, dot(q, q)); // max.w carries max |p - c|^2 so K1 can write the exact layoutRadius (spec 3.3)
1330
+ }
1331
+ if (free) { dl = length(dp); fr = 1u; }
1332
+ let tSum = wg_reduce_vec4(sumv, lid.x, 0u);
1333
+ let tLo = wg_reduce_vec4(lo, lid.x, 1u);
1334
+ let tHi = wg_reduce_vec4(hi, lid.x, 2u);
1335
+ let tDl = wg_reduce_f32(dl, lid.x, 0u);
1336
+ let tFr = wg_reduce_u32(fr, lid.x, 0u);
1337
+ let tKe = wg_reduce_f32(ke, lid.x, 0u);
1338
+ if (lid.x == 0u) {
1339
+ let g = group_id(wid);
1340
+ partials[g].sum = tSum;
1341
+ partials[g].min = tLo;
1342
+ partials[g].max = tHi;
1343
+ partials[g].dispFree = vec2f(tDl, f32(tFr));
1344
+ if (APPLY != 0u) { partials[g].swingTraction = vec2f(tKe, 0.0); } // overwrites K3's epilogue: K4 never runs under FR or the preset (PD-4)
1345
+ }
1346
+ }`,WP=`
1347
+ var<workgroup> tile: array<vec4f, WG>; // xyz + mass, 4 KiB at WG = 256
1348
+
1349
+ fn load_force(i: u32) -> vec3f { return vec3f(force[3u * i], force[3u * i + 1u], force[3u * i + 2u]); }
1350
+ fn store_force(i: u32, f: vec3f) {
1351
+ force[3u * i] = f.x;
1352
+ force[3u * i + 1u] = f.y;
1353
+ force[3u * i + 2u] = f.z;
1354
+ }
1355
+ fn load_old(i: u32) -> vec3f { return vec3f(oldForce[3u * i], oldForce[3u * i + 1u], oldForce[3u * i + 2u]); }
1356
+ fn kick_magnitude(mi: f32, mj: f32) -> f32 { // the law's magnitude at d = FA2_DIST_FLOOR (PD-10)
1357
+ if (LAW == 1u) { return P.frK * P.frK / FA2_DIST_FLOOR; }
1358
+ if (LAW == 2u) { return -P.coulomb * mi * mj / FA2_DIST_FLOOR_SQ; }
1359
+ return P.scalingRatio * mi * mj / FA2_DIST_FLOOR;
1360
+ }
1361
+ fn gravity_force(pi: vec4f) -> vec3f { // spec 7.9: centroid (GRAVITY_CENTER 0) or origin (1); regular or strong
1362
+ var q = pi.xyz;
1363
+ if (GRAVITY_CENTER == 0u) { q = pi.xyz - S.centroid.xyz; }
1364
+ if (STRONG_GRAVITY) { return -P.gravity * pi.w * q; }
1365
+ let d = length(q);
1366
+ if (d > FA2_DIST_FLOOR) { return -P.gravity * pi.w * q / d; }
1367
+ return vec3f(0.0);
1368
+ }
1369
+
1370
+ @compute @workgroup_size(WG)
1371
+ fn repulsion(
1372
+ @builtin(workgroup_id) wid: vec3<u32>,
1373
+ @builtin(local_invocation_id) lid: vec3<u32>,
1374
+ @builtin(num_workgroups) nwg: vec3<u32>,
1375
+ ) {
1376
+ // issue #87: pass p of the tile range is dispatched with p + 1 z slices; only the last slice works, so the pass
1377
+ // index needs no uniform. Uniform: keyed on workgroup_id and num_workgroups only.
1378
+ if (wid.z + 1u < nwg.z) { return; }
1379
+ let i = linear_id(wid, lid.x);
1380
+ let valid = i < P.n;
1381
+ var pi = vec4f(0.0);
1382
+ if (valid) { pi = pos[i]; }
1383
+ var f = vec3f(0.0);
1384
+ let tiles = (P.n + WG - 1u) / WG;
1385
+ let tileBegin = (nwg.z - 1u) * EXACT_TILES_PER_PASS;
1386
+ let tileEnd = min(tiles, tileBegin + EXACT_TILES_PER_PASS);
1387
+ for (var t = tileBegin; t < tileEnd; t = t + 1u) {
1388
+ let j = t * WG + lid.x;
1389
+ if (j < P.n) { tile[lid.x] = pos[j]; } else { tile[lid.x] = vec4f(0.0); } // guarded fill; mass 0 marks the pad
1390
+ workgroupBarrier(); // uniform: every invocation reaches it
1391
+ for (var s = 0u; s < WG; s = s + 1u) {
1392
+ let o = tile[s];
1393
+ let jj = t * WG + s;
1394
+ if (o.w > 0.0 && jj != i) { // mass > 0 for every real node, 0 for the pad
1395
+ let d = pi.xyz - o.xyz;
1396
+ var d2 = dot(d, d);
1397
+ if (d2 < FA2_COINCIDENT_SQ) { // coincident: antisymmetric unit kick of the law's magnitude at d = 0.01 (7.2; PD-10)
1398
+ f = f + kick_dir(i, jj, P.dim) * kick_magnitude(pi.w, o.w);
1399
+ continue;
1400
+ }
1401
+ if (LAW == 0u) { d2 = max(d2, FA2_DIST_FLOOR_SQ); } // FA2 alone floors d >= 0.01 (7.2); FR and coulomb are unfloored (7.20)
1402
+ let k = P.scalingRatio * pi.w * o.w;
1403
+ if (LAW == 0u) { f = f + d * (k / d2); } // LAW 0 (FA2): |F| = k m_i m_j / d along d / d
1404
+ if (LAW == 1u) { f = f + d * (P.frK * P.frK / d2); } // LAW 1 (FR, 7.20): |F| = k^2 / d, mass ignored
1405
+ if (LAW == 2u) { f = f + d * (-P.coulomb * pi.w * o.w / (d2 * sqrt(d2))); } // LAW 2 (coulomb, ngraph generateQuadTree.js:131-132): |F| = -g m_i m_j / d^2
1406
+ }
1407
+ }
1408
+ workgroupBarrier();
1409
+ }
1410
+ if (tileEnd < tiles) { // an earlier pass: its partial sum only (uniform: P.n, nwg)
1411
+ if (valid) { store_force(i, load_force(i) + f); }
1412
+ return;
1413
+ }
1414
+ // epilogue (7.9, 7.10): gravity and force += under the guard, the swing / traction reduction outside it
1415
+ var sw = 0.0;
1416
+ var tr = 0.0;
1417
+ if (valid) {
1418
+ f = f + gravity_force(pi);
1419
+ let fnew = load_force(i) + f;
1420
+ store_force(i, fnew);
1421
+ if (SWING_MODE == 1u) { // NetworkX: positions and forces mixed, every node (7.2)
1422
+ sw = pi.w * length(pi.xyz - fnew);
1423
+ tr = 0.5 * pi.w * length(pi.xyz + fnew);
1424
+ } else if (!mask_bit(fixedMask[i >> 5u], i)) { // paper: free nodes only (Gephi ForceAtlas2.java 283-293)
1425
+ let fold = load_old(i);
1426
+ sw = pi.w * length(fnew - fold);
1427
+ tr = 0.5 * pi.w * length(fnew + fold);
1428
+ }
1429
+ }
1430
+ let t = wg_reduce_vec4(vec4f(sw, tr, 0.0, 0.0), lid.x, 0u); // uniform control flow: 256 -> 1
1431
+ if (lid.x == 0u) { partials[group_id(wid)].swingTraction = t.xy; }
1432
+ }
1433
+ `,VP=`
1434
+ @compute @workgroup_size(WG)
1435
+ fn speed_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
1436
+ let groups = (P.n + WG - 1u) / WG;
1437
+ var st = vec2f(0.0);
1438
+ for (var g = lid.x; g < groups; g = g + WG) { st = st + partials[g].swingTraction; } // sequential per lane: deterministic
1439
+ let t = wg_reduce_vec4(vec4f(st, 0.0, 0.0), lid.x, 0u);
1440
+ if (lid.x == 0u) {
1441
+ var swing = t.x;
1442
+ var traction = t.y;
1443
+ if (SWING_MODE == 1u) { swing = S.swing + t.x; traction = S.traction + t.y; } // NetworkX accumulates across iterations from 1
1444
+ let n = f32(P.n);
1445
+ let optJitter = 0.05 * sqrt(n);
1446
+ let minJitter = sqrt(optJitter);
1447
+ let maxJitter = 10.0;
1448
+ let tr = max(traction, 1.0e-30); // guards the division only (7.10)
1449
+ let other = min(maxJitter, optJitter * traction / (n * n));
1450
+ var jitter = P.jitterTolerance * max(minJitter, other);
1451
+ var eff = S.speedEfficiency;
1452
+ if (swing > 2.0 * tr) { // swing / traction > 2 in the exact form (contract 4.5 CONTRACT DECISION K4-1: 2 x is exact, a WGSL f32 division is not)
1453
+ if (eff > 0.05) { eff = eff * 0.5; } // the CPU's conditional multiply (7.2)
1454
+ jitter = max(jitter, P.jitterTolerance);
1455
+ }
1456
+ let targetSpeed = select(jitter * eff * traction / swing, 1.0e30, swing == 0.0); // +Inf in the port; 1e30 gives the same min() below (\`target\` is reserved)
1457
+ if (swing > jitter * traction) {
1458
+ if (eff > 0.05) { eff = eff * 0.7; }
1459
+ } else if (S.speed < 1000.0) {
1460
+ eff = eff * 1.3;
1461
+ }
1462
+ S.speed = S.speed + min(targetSpeed - S.speed, 0.5 * S.speed);
1463
+ S.speedEfficiency = eff;
1464
+ S.swing = swing;
1465
+ S.traction = traction;
1466
+ T[P.iterationIndex].swing = swing;
1467
+ T[P.iterationIndex].traction = traction;
1468
+ T[P.iterationIndex].speed = S.speed;
1469
+ T[P.iterationIndex].speedEfficiency = eff;
1470
+ }
1471
+ }
1472
+ `,jP=`// K1: folds the previous integrate's partials into the state block (spec 7.4); one workgroup
1473
+ @compute @workgroup_size(WG)
1474
+ fn stats_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
1475
+ let groups = (P.n + WG - 1u) / WG;
1476
+ let fold = (P.flags & FA2_FLAG_FIRST) == 0u; // the first iteration after load() keeps the host-written state
1477
+ var sum = vec4f(0.0);
1478
+ var lo = vec4f(F32_MAX);
1479
+ var hi = vec4f(-F32_MAX);
1480
+ var disp = 0.0;
1481
+ var free = 0u;
1482
+ var ke = 0.0;
1483
+ if (fold) {
1484
+ for (var g = lid.x; g < groups; g = g + WG) { // sequential per lane in index order: deterministic
1485
+ let q = partials[g];
1486
+ sum = sum + q.sum;
1487
+ lo = min(lo, q.min);
1488
+ hi = max(hi, q.max);
1489
+ disp = disp + q.dispFree.x;
1490
+ free = free + u32(q.dispFree.y);
1491
+ ke = ke + q.swingTraction.x;
1492
+ }
1493
+ }
1494
+ let tSum = wg_reduce_vec4(sum, lid.x, 0u);
1495
+ let tLo = wg_reduce_vec4(lo, lid.x, 1u);
1496
+ let tHi = wg_reduce_vec4(hi, lid.x, 2u);
1497
+ let tDisp = wg_reduce_f32(disp, lid.x, 0u);
1498
+ let tFree = wg_reduce_u32(free, lid.x, 0u);
1499
+ let tKe = wg_reduce_f32(ke, lid.x, 0u);
1500
+ if (lid.x == 0u) {
1501
+ if (fold) {
1502
+ let n = f32(P.n);
1503
+ let c = tSum.xyz / n;
1504
+ S.centroid = vec4f(c, 0.0);
1505
+ S.rmsRadius = sqrt(max(tSum.w, 0.0) / n); // RMS radius about the previous centroid (7.17)
1506
+ S.min = vec4f(tLo.xyz, 0.0);
1507
+ S.max = vec4f(tHi.xyz, 0.0);
1508
+ S.radius = sqrt(max(tHi.w, 0.0)); // max |p - centroid| about the same previous centroid as rmsRadius (K5 puts |q|^2 in max.w)
1509
+ let meanDisp = select(tDisp / f32(tFree), 0.0, tFree == 0u); // all-fixed: 0, never NaN (7.4)
1510
+ S.meanDisplacement = meanDisp;
1511
+ S.settledCount = select(0u, S.settledCount + 1u, meanDisp <= min(P.settleThreshold * S.rmsRadius, P.settleFloor)); // relative AND absolute (issue #97)
1512
+ }
1513
+ S.iteration = S.iteration + 1u;
1514
+ T[P.iterationIndex].meanDisplacement = S.meanDisplacement;
1515
+ T[P.iterationIndex].settledCount = S.settledCount;
1516
+ T[P.iterationIndex].iteration = S.iteration;
1517
+ if (P.gridMax > 0u) { // the grid tier (7.7): the robust extent, the cell size, eps, last iteration's counts, the hub counter reset (PD-14)
1518
+ let cells = P.gridMax * P.gridMax * select(1u, P.gridMax, P.dim == 3u);
1519
+ if (fold) {
1520
+ let box = (S.max.xyz - S.min.xyz) * GRID_BBOX_MARGIN;
1521
+ var bboxExtent = max(box.x, box.y);
1522
+ if (P.dim == 3u) { bboxExtent = max(bboxExtent, box.z); }
1523
+ let extent = max(min(bboxExtent, P.extentFactor * S.rmsRadius), GRID_EXTENT_FLOOR); // min(bbox, extentFactor x rms), floored (7.7)
1524
+ let cellSize = extent / f32(P.gridMax);
1525
+ S.gridMin = vec4f(S.centroid.xyz - vec3f(0.5 * extent), cellSize); // gridMin.w carries cellSize
1526
+ S.invCellSize = 1.0 / cellSize;
1527
+ S.eps = 0.25 * cellSize;
1528
+ }
1529
+ var outside = 0u; // the previous iteration's pseudo-cell counts, one per orthant (issue #90; 0 after load)
1530
+ for (var o = 0u; o < select(4u, 8u, P.dim == 3u); o = o + 1u) { outside = outside + cellHist[cells + o]; }
1531
+ S.outsideGrid = outside;
1532
+ S.maxCellOccupancy = atomicLoad(&hubCounters[1]);
1533
+ atomicStore(&hubCounters[0], 0u);
1534
+ atomicStore(&hubCounters[1], 0u);
1535
+ }
1536
+ if (STATS_MODE == 1u) { // FR: this iteration's temperature (7.20) into the state and the trace
1537
+ if ((P.flags & FA2_FLAG_ADAPTIVE) != 0u) { // adaptive cooling (Yifan Hu 2005 3.2): tKe is the previous iteration's sum |F|^2 over free nodes
1538
+ if (fold) {
1539
+ var t = S.temperature;
1540
+ if (tKe < S.frEnergy) {
1541
+ S.frProgress = S.frProgress + 1u;
1542
+ if (S.frProgress >= FR_COOLING_PATIENCE) { S.frProgress = 0u; t = t / FR_COOLING_STEP; }
1543
+ } else {
1544
+ S.frProgress = 0u;
1545
+ t = t * FR_COOLING_STEP;
1546
+ }
1547
+ S.frEnergy = tKe;
1548
+ S.temperature = t;
1549
+ }
1550
+ } else {
1551
+ S.temperature = P.temperature;
1552
+ }
1553
+ T[P.iterationIndex].modelScalar = S.temperature;
1554
+ }
1555
+ if (STATS_MODE == 2u) { // spring-electrical: the kinetic energy K5 folded into partials B (PD-4); 0 on the first iteration after load()
1556
+ S.kineticEnergy = tKe;
1557
+ T[P.iterationIndex].modelScalar = tKe;
1558
+ }
1559
+ }
1560
+ }`,qP=`@compute @workgroup_size(WG)
1561
+ fn to_scene(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1562
+ let i = linear_id(wid, lid.x);
1563
+ if (i >= P.n) { return; }
1564
+ let s = pos[i].xyz * P.scale + P.center.xyz;
1565
+ scene[3u * i] = s.x;
1566
+ scene[3u * i + 1u] = s.y;
1567
+ scene[3u * i + 2u] = select(s.z, P.center.z, P.dim == 2u); // 2D writes z = center.z on every readback (7.13)
1568
+ }`,HP=`
1569
+ @compute @workgroup_size(WG)
1570
+ fn fill(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1571
+ let i = linear_id(wid, lid.x);
1572
+ if (i >= P.count) { return; }
1573
+ dst[i] = select(P.value, i + P.value, P.mode == 1u);
1574
+ }
1575
+ `,KP=`
1576
+ @compute @workgroup_size(WG)
1577
+ fn frontier_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
1578
+ if (lid.x != 0u) { return; } // one lane; no barrier follows (3.5 rule 1)
1579
+ if (P.role == 0u) { // the level boundary
1580
+ if (atomicLoad(&counters[15]) != 0u) { // done already: a no-op level the host recorded past the end
1581
+ atomicStore(&counters[24], 0u); // the path word is the only word that moves (P8-T6's levels formula reads the rest)
1582
+ return;
1583
+ }
1584
+ let finished = atomicLoad(&counters[0]);
1585
+ let next = atomicLoad(&counters[1]);
1586
+ let degSum = atomicLoad(&counters[2]);
1587
+ let nextDeg = atomicLoad(&counters[25]); // deg(F_b), summed by bfs-next-degree when F_b was claimed (issue #391)
1588
+ atomicStore(&counters[3], finished); // prevFrontierCount
1589
+ atomicStore(&counters[4], degSum); // prevDegreeSum
1590
+ atomicStore(&counters[0], next); // the rotation
1591
+ atomicStore(&counters[1], 0u);
1592
+ atomicStore(&counters[2], 0u);
1593
+ atomicStore(&counters[25], 0u); // the next level's claims sum from 0
1594
+ atomicStore(&counters[8], 0u); // edgeCount
1595
+ atomicStore(&counters[9], 0u); // edgeCountUnclamped
1596
+ atomicStore(&counters[12], atomicLoad(&counters[12]) + next); // visitedCount
1597
+ if (P.firstOfSubmit >= 1u) { // b = the boundary's index inside its submit, clamped (P8-T8, PD-18): F_b was inside the submit's rebuilt sums iff b >= 1
1598
+ atomicStore(&counters[5], atomicLoad(&counters[5]) - next); // unvisitedCount, exact (bfs-next-degree keeps unvisitedDegreeSum exact)
1599
+ }
1600
+ let level = atomicLoad(&counters[11]) + 1u; // the seed is U32_MAX, so the first boundary lands on 0
1601
+ atomicStore(&counters[11], level);
1602
+ let done = (next == 0u) || (level >= P.maxDepth);
1603
+ atomicStore(&counters[15], select(0u, 1u, done));
1604
+ var direction = atomicLoad(&counters[14]);
1605
+ if (P.mode == 1u) {
1606
+ direction = 0u; // top-down only (the test seam)
1607
+ } else if (direction == 0u) {
1608
+ let bottomUpReads = select(max(atomicLoad(&counters[5]), atomicLoad(&counters[6]) / P.alpha), 0u, P.mode == 2u); // what a sweep is expected to read: at least one in-arc per unvisited vertex (issue #1358); mode 2 (the test seam) forces the switch
1609
+ if (nextDeg > bottomUpReads && next > finished) { direction = 1u; } // m_f > the sweep's reads and growing, m_f the degree of the frontier about to be expanded
1610
+ } else {
1611
+ if (next * P.beta < atomicLoad(&counters[5]) && next < finished) { direction = 0u; } // next * beta < unvisited and shrinking
1612
+ }
1613
+ if (direction != atomicLoad(&counters[14])) { atomicStore(&counters[13], atomicLoad(&counters[13]) + 1u); } // switches
1614
+ var path = 0u; // word 24: what the level's kernels run (0 nothing, 1 two-phase, 2 fused, 3 bottom-up; role 1 writes 4 for the retry)
1615
+ if (done) {
1616
+ path = 0u;
1617
+ } else if (direction == 1u) { // the bottom-up level (P8-T8): the bits fill, the bitset build, the sweep
1618
+ path = 3u;
1619
+ atomicStore(&counters[19], atomicLoad(&counters[19]) + 1u);
1620
+ } else if (next < P.fusedMax) { // P8-T7 makes this branch reachable (fusedMax is 0 until then)
1621
+ path = 2u; // bfs-fused: one WORKGROUP per frontier entry
1622
+ atomicStore(&counters[17], atomicLoad(&counters[17]) + 1u);
1623
+ } else {
1624
+ path = 1u; // advance-expand, then role 1 and bfs-contract
1625
+ }
1626
+ atomicStore(&counters[14], direction);
1627
+ atomicStore(&counters[24], path);
1628
+ } else if (P.role == 1u) { // the edge queue is filled
1629
+ if (atomicLoad(&counters[24]) != 1u) { // role 0 did not choose the two-phase path (done, fused or bottom-up): nothing to clamp, nothing to count
1630
+ return;
1631
+ }
1632
+ let clamped = min(atomicLoad(&counters[8]), P.edgeCapacity);
1633
+ atomicStore(&counters[8], clamped);
1634
+ if (atomicLoad(&counters[9]) > P.edgeCapacity) { // PD-23: the fused retry
1635
+ atomicStore(&counters[24], 4u); // the path word: bfs-fused runs the retry over frontierCount, bfs-contract nothing
1636
+ atomicStore(&counters[10], atomicLoad(&counters[10]) + 1u);
1637
+ atomicStore(&counters[17], atomicLoad(&counters[17]) + 1u);
1638
+ } else {
1639
+ atomicStore(&counters[18], atomicLoad(&counters[18]) + 1u); // twoPhaseLevels counts the CHOICE role 0 made, even for zero edges (P8-T7 Step 4's invariant)
1640
+ }
1641
+ } else if (P.role == 2u) { // the SSSP round boundary (P8-T9, PD-20): which pile this round relaxes
1642
+ atomicStore(&counters[8], 0u); // the dedupe counts (words 8 and 9, the SSSP sense) and the path word: nothing unless a pile is chosen below
1643
+ atomicStore(&counters[9], 0u);
1644
+ atomicStore(&counters[24], 0u);
1645
+ if (atomicLoad(&counters[15]) != 0u) { // done already: a no-op round the host recorded past the end (rule 1)
1646
+ return;
1647
+ }
1648
+ let nearRaw = atomicLoad(&counters[1]); // the raw near half's appends, unclamped
1649
+ let farRaw = atomicLoad(&counters[21]); // the raw far half's appends, unclamped
1650
+ if (nearRaw > P.edgeCapacity || farRaw > P.edgeCapacity) { // a pile overflowed its half: the host raises E_TOO_LARGE
1651
+ atomicStore(&counters[15], 2u);
1652
+ return;
1653
+ }
1654
+ if (nearRaw != 0u) { // a near round: dedupe the near half into nearIn
1655
+ atomicStore(&counters[0], 0u); // the deduped near count, accumulated by dedupe-filter
1656
+ atomicStore(&counters[14], 0u); // mode 0
1657
+ atomicStore(&counters[8], nearRaw); // the near dedupe's count word (dedupe-claim, dedupe-filter over the near half)
1658
+ atomicStore(&counters[24], 5u); // the path word: sssp-relax role 0 runs, role 1 nothing
1659
+ atomicStore(&counters[11], atomicLoad(&counters[11]) + 1u); // rounds dispatched (the done boundary is not counted)
1660
+ } else if (farRaw != 0u) { // the near pile is empty: raise the threshold and re-bucket the far pile
1661
+ let threshold = bitcast<f32>(atomicLoad(&counters[22]));
1662
+ let raised = threshold + bitcast<f32>(atomicLoad(&counters[23])); // ONE f32 add on the bit patterns (PD-9)
1663
+ if (raised == threshold) { // the delta is below the threshold's ulp: the host raises E_UNSUPPORTED
1664
+ atomicStore(&counters[15], 3u);
1665
+ return;
1666
+ }
1667
+ atomicStore(&counters[4], atomicLoad(&counters[22])); // prevThresholdBits: what the pass-through drops below
1668
+ atomicStore(&counters[22], bitcast<u32>(raised));
1669
+ atomicStore(&counters[20], 0u); // the deduped far count, accumulated by dedupe-filter
1670
+ atomicStore(&counters[14], 1u); // mode 1
1671
+ atomicStore(&counters[9], farRaw); // the far dedupe's count word (dedupe-claim, dedupe-filter over the far half)
1672
+ atomicStore(&counters[24], 6u); // the path word: sssp-relax role 1 runs, role 0 nothing
1673
+ atomicStore(&counters[11], atomicLoad(&counters[11]) + 1u);
1674
+ } else { // both piles empty: finished
1675
+ atomicStore(&counters[15], 1u);
1676
+ }
1677
+ } else if (P.role == 3u) { // the piles are deduped: restart the raw half the round consumed
1678
+ if (atomicLoad(&counters[15]) != 0u) { return; } // role 2 chose no pile this round
1679
+ if (atomicLoad(&counters[14]) == 0u) {
1680
+ atomicStore(&counters[1], 0u); // the raw near half restarts (sssp-relax role 0 sizes itself from word 0)
1681
+ } else {
1682
+ atomicStore(&counters[21], 0u); // the raw far half restarts (the pass-through re-appends what stays far; role 1 sizes itself from word 20)
1683
+ }
1684
+ }
1685
+ }
1686
+ `,YP=`
1687
+ fn grid_cells() -> u32 { return P.gridMax * P.gridMax * select(1u, P.gridMax, P.dim == 3u); }
1688
+
1689
+ @compute @workgroup_size(WG)
1690
+ fn grid_cell_key(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1691
+ let i = linear_id(wid, lid.x);
1692
+ if (i >= P.n) { return; } // no barrier follows
1693
+ let cells = grid_cells();
1694
+ let gf = f32(P.gridMax);
1695
+ let q = (pos[i].xyz - S.gridMin.xyz) * S.invCellSize; // PD-10: never a division
1696
+ let c = vec3<i32>(floor(clamp(q, vec3f(-1.0), vec3f(gf + 1.0))));
1697
+ let g = i32(P.gridMax);
1698
+ var inside = c.x >= 0 && c.x < g && c.y >= 0 && c.y < g;
1699
+ if (P.dim == 3u) { inside = inside && c.z >= 0 && c.z < g; }
1700
+ var key = cells + select(0u, 1u, c.x >= g / 2) + select(0u, 2u, c.y >= g / 2); // an outside pseudo-cell: its orthant (issue #90)
1701
+ if (P.dim == 3u) { key = key + select(0u, 4u, c.z >= g / 2); }
1702
+ if (inside) {
1703
+ key = u32(c.x) + P.gridMax * u32(c.y);
1704
+ if (P.dim == 3u) { key = key + P.gridMax * P.gridMax * u32(c.z); }
1705
+ }
1706
+ cellKey[i] = key;
1707
+ cellVal[i] = i;
1708
+ }
1709
+ `,XP=`
1710
+ fn grid_cells() -> u32 { return P.gridMax * P.gridMax * select(1u, P.gridMax, P.dim == 3u); }
1711
+
1712
+ @compute @workgroup_size(WG)
1713
+ fn grid_centroid(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1714
+ let c = linear_id(wid, lid.x);
1715
+ if (c >= grid_cells() + select(4u, 8u, P.dim == 3u)) { return; } // cells [0, cells + 2^dim): the pseudo-cells follow the real ones; no barrier follows
1716
+ let start = cellStart[c];
1717
+ let count = cellStart[c + 1u] - start;
1718
+ atomicMax(&hubCounters[1], count); // maxCellOccupancy, read by K1 next iteration
1719
+ if (count > GRID_HUB_CELL) { // a hub cell: G4b sums it (PD-13)
1720
+ hubList[atomicAdd(&hubCounters[0], 1u)] = c;
1721
+ return;
1722
+ }
1723
+ var acc = vec4f(0.0);
1724
+ for (var k = start; k < start + count; k = k + 1u) { // sorted order: deterministic
1725
+ let p = pos[sortedIdx[k]];
1726
+ acc = acc + vec4f(p.xyz * p.w, p.w); // (sum m x, sum m y, sum m z, sum m)
1727
+ }
1728
+ pyramid[c] = acc;
1729
+ }
1730
+ `,QP=`
1731
+ @compute @workgroup_size(WG)
1732
+ fn grid_centroid_hub(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1733
+ let h = group_id(wid);
1734
+ let valid = h < hubCount[0]; // a workgroup past the count sums nothing
1735
+ var c = 0u;
1736
+ var start = 0u;
1737
+ var count = 0u;
1738
+ if (valid) {
1739
+ c = hubList[h];
1740
+ start = cellStart[c];
1741
+ count = cellStart[c + 1u] - start;
1742
+ }
1743
+ var acc = vec4f(0.0);
1744
+ for (var k = start + lid.x; k < start + count; k = k + WG) { // strided over the cell's sorted range
1745
+ let p = pos[sortedIdx[k]];
1746
+ acc = acc + vec4f(p.xyz * p.w, p.w);
1747
+ }
1748
+ let t = wg_reduce_vec4(acc, lid.x, 0u); // uniform control flow: 256 -> 1
1749
+ if (valid && lid.x == 0u) { pyramid[c] = t; }
1750
+ }
1751
+ `,JP=`
1752
+ @compute @workgroup_size(WG)
1753
+ fn grid_downsample(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1754
+ let pc = linear_id(wid, lid.x); // the parent cell inside its level
1755
+ if (pc >= P.parentCells) { return; } // no barrier follows
1756
+ let side = P.parentSide;
1757
+ let cs = 2u * side; // the child level's side
1758
+ let px = pc % side;
1759
+ let py = (pc / side) % side;
1760
+ let pz = pc / (side * side);
1761
+ var acc = vec4f(0.0);
1762
+ for (var dz = 0u; dz < P.depth; dz = dz + 1u) {
1763
+ for (var dy = 0u; dy < 2u; dy = dy + 1u) {
1764
+ for (var dx = 0u; dx < 2u; dx = dx + 1u) {
1765
+ let child = (2u * px + dx) + cs * ((2u * py + dy) + cs * (2u * pz + dz));
1766
+ acc = acc + pyramid[P.childBase + child];
1767
+ }
1768
+ }
1769
+ }
1770
+ pyramid[P.parentBase + pc] = acc;
1771
+ }
1772
+ `,ZP=`
1773
+ fn load_force(i: u32) -> vec3f { return vec3f(force[3u * i], force[3u * i + 1u], force[3u * i + 2u]); }
1774
+ fn store_force(i: u32, f: vec3f) {
1775
+ force[3u * i] = f.x;
1776
+ force[3u * i + 1u] = f.y;
1777
+ force[3u * i + 2u] = f.z;
1778
+ }
1779
+ fn grid_cells() -> u32 { return P.gridMax * P.gridMax * select(1u, P.gridMax, P.dim == 3u); }
1780
+ fn grid_side(level: u32) -> u32 { return P.gridMax >> level; }
1781
+ fn outside_cells() -> u32 { return select(4u, 8u, P.dim == 3u); } // one pseudo-cell per orthant (issue #90)
1782
+ fn level_base(level: u32) -> u32 { // the pyramid index of level L's cell 0 (level 0 carries the pseudo-cells at cells ..)
1783
+ var base = 0u;
1784
+ for (var l = 0u; l < level; l = l + 1u) {
1785
+ let s = grid_side(l);
1786
+ base = base + s * s * select(1u, s, P.dim == 3u) + select(0u, outside_cells(), l == 0u);
1787
+ }
1788
+ return base;
1789
+ }
1790
+ fn cell_at(level: u32, cx: i32, cy: i32, cz: i32) -> u32 {
1791
+ let s = grid_side(level);
1792
+ return level_base(level) + u32(cx) + s * (u32(cy) + select(0u, s * u32(cz), P.dim == 3u));
1793
+ }
1794
+ fn cell_force(pi: vec4f, q: vec4f) -> vec3f { // one far-field term, softened by state.eps (7.7)
1795
+ if (q.w <= 0.0) { return vec3f(0.0); } // an empty cell
1796
+ let d = pi.xyz - q.xyz / q.w; // to the mass-weighted centroid
1797
+ var d2 = dot(d, d);
1798
+ if (LAW == 0u) { d2 = max(d2, FA2_DIST_FLOOR_SQ); } // FA2 alone floors d >= 0.01, as K3 and G7 do (issue #89); FR and coulomb are unfloored (7.20)
1799
+ d2 = d2 + S.eps * S.eps;
1800
+ if (LAW == 1u) { return d * (P.frK * P.frK * q.w / d2); } // LAW 1 (FR, 7.20): k^2 / d per node, q.w nodes at the centroid
1801
+ if (LAW == 2u) { return d * (-P.coulomb * pi.w * q.w / (d2 * sqrt(d2))); } // LAW 2 (coulomb): -g m_i M_cell / d^2
1802
+ return d * (P.scalingRatio * pi.w * q.w / d2); // LAW 0 (FA2): |F| = k m_i M_cell / d
1803
+ }
1804
+
1805
+ @compute @workgroup_size(WG)
1806
+ fn grid_far_field(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1807
+ let t = linear_id(wid, lid.x);
1808
+ if (t >= P.n) { return; } // no barrier follows
1809
+ let i = sortedIdx[t]; // sorted order (D24)
1810
+ let pi = pos[i];
1811
+ let gf = f32(P.gridMax);
1812
+ let q = (pi.xyz - S.gridMin.xyz) * S.invCellSize; // PD-10
1813
+ var c0 = vec3<i32>(floor(clamp(q, vec3f(-1.0), vec3f(gf + 1.0))));
1814
+ if (P.dim == 2u) { c0.z = 0; } // 2D: one z plane; the loops below visit cz = 0 only, so the 3x3 test must see cz - 0
1815
+ let g = i32(P.gridMax);
1816
+ var inside = c0.x >= 0 && c0.x < g && c0.y >= 0 && c0.y < g;
1817
+ if (P.dim == 3u) { inside = inside && c0.z >= 0 && c0.z < g; }
1818
+ let top = P.levels - 1u;
1819
+ let ts = i32(grid_side(top)); // the coarsest side (4)
1820
+ let zTop = select(0, ts - 1, P.dim == 3u); // z ranges: one plane in 2D
1821
+ var f = vec3f(0.0);
1822
+ if (inside) {
1823
+ let ct = c0 / i32(1u << top); // the node's coarsest cell
1824
+ for (var cz = 0; cz <= zTop; cz = cz + 1) {
1825
+ for (var cy = 0; cy < ts; cy = cy + 1) {
1826
+ for (var cx = 0; cx < ts; cx = cx + 1) {
1827
+ if (abs(cx - ct.x) <= 1 && abs(cy - ct.y) <= 1 && abs(cz - ct.z) <= 1) { continue; } // the 3x3(x3) is finer levels' work
1828
+ f = f + cell_force(pi, pyramid[cell_at(top, cx, cy, cz)]);
1829
+ }
1830
+ }
1831
+ }
1832
+ for (var l = top; l > 0u; l = l - 1u) { // level l - 1: the parent's 3x3 at level l, refined, minus this level's own 3x3
1833
+ let level = l - 1u;
1834
+ let cl = c0 / i32(1u << level);
1835
+ let cp = cl / 2;
1836
+ let side = i32(grid_side(level));
1837
+ let zLo = select(0, max(0, 2 * (cp.z - 1)), P.dim == 3u);
1838
+ let zHi = select(0, min(side - 1, 2 * (cp.z + 1) + 1), P.dim == 3u);
1839
+ for (var cz = zLo; cz <= zHi; cz = cz + 1) {
1840
+ for (var cy = max(0, 2 * (cp.y - 1)); cy <= min(side - 1, 2 * (cp.y + 1) + 1); cy = cy + 1) {
1841
+ for (var cx = max(0, 2 * (cp.x - 1)); cx <= min(side - 1, 2 * (cp.x + 1) + 1); cx = cx + 1) {
1842
+ if (abs(cx - cl.x) <= 1 && abs(cy - cl.y) <= 1 && abs(cz - cl.z) <= 1) { continue; }
1843
+ f = f + cell_force(pi, pyramid[cell_at(level, cx, cy, cz)]);
1844
+ }
1845
+ }
1846
+ }
1847
+ }
1848
+ for (var o = 0u; o < outside_cells(); o = o + 1u) { // every outside pseudo-cell: one far-field term per orthant
1849
+ f = f + cell_force(pi, pyramid[grid_cells() + o]);
1850
+ }
1851
+ } else {
1852
+ for (var cz = 0; cz <= zTop; cz = cz + 1) { // an outside node: the coarsest level in full, no pseudo-cell (G7 sums them pair by pair)
1853
+ for (var cy = 0; cy < ts; cy = cy + 1) {
1854
+ for (var cx = 0; cx < ts; cx = cx + 1) {
1855
+ f = f + cell_force(pi, pyramid[cell_at(top, cx, cy, cz)]);
1856
+ }
1857
+ }
1858
+ }
1859
+ }
1860
+ store_force(i, load_force(i) + f);
1861
+ }
1862
+ `,ex=`
1863
+ fn load_force(i: u32) -> vec3f { return vec3f(force[3u * i], force[3u * i + 1u], force[3u * i + 2u]); }
1864
+ fn store_force(i: u32, f: vec3f) {
1865
+ force[3u * i] = f.x;
1866
+ force[3u * i + 1u] = f.y;
1867
+ force[3u * i + 2u] = f.z;
1868
+ }
1869
+ fn load_old(i: u32) -> vec3f { return vec3f(oldForce[3u * i], oldForce[3u * i + 1u], oldForce[3u * i + 2u]); }
1870
+ fn gravity_force(pi: vec4f) -> vec3f { // spec 7.9: centroid (GRAVITY_CENTER 0) or origin (1); regular or strong
1871
+ var q = pi.xyz;
1872
+ if (GRAVITY_CENTER == 0u) { q = pi.xyz - S.centroid.xyz; }
1873
+ if (STRONG_GRAVITY) { return -P.gravity * pi.w * q; }
1874
+ let d = length(q);
1875
+ if (d > FA2_DIST_FLOOR) { return -P.gravity * pi.w * q / d; }
1876
+ return vec3f(0.0);
1877
+ }
1878
+ fn grid_cells() -> u32 { return P.gridMax * P.gridMax * select(1u, P.gridMax, P.dim == 3u); }
1879
+ fn kick_magnitude(mi: f32, mj: f32) -> f32 { // the law's magnitude at d = FA2_DIST_FLOOR (the P5 plan's PD-10)
1880
+ if (LAW == 1u) { return P.frK * P.frK / FA2_DIST_FLOOR; }
1881
+ if (LAW == 2u) { return -P.coulomb * mi * mj / FA2_DIST_FLOOR_SQ; }
1882
+ return P.scalingRatio * mi * mj / FA2_DIST_FLOOR;
1883
+ }
1884
+ fn pair_force(i: u32, pi: vec4f, jj: u32, o: vec4f) -> vec3f { // the exact pair law of K3 (7.6, 7.20): the floor (FA2 only), the coincident kick
1885
+ let d = pi.xyz - o.xyz;
1886
+ var d2 = dot(d, d);
1887
+ if (d2 < FA2_COINCIDENT_SQ) { return kick_dir(i, jj, P.dim) * kick_magnitude(pi.w, o.w); }
1888
+ if (LAW == 0u) { d2 = max(d2, FA2_DIST_FLOOR_SQ); }
1889
+ let k = P.scalingRatio * pi.w * o.w;
1890
+ if (LAW == 1u) { return d * (P.frK * P.frK / d2); }
1891
+ if (LAW == 2u) { return d * (-P.coulomb * pi.w * o.w / (d2 * sqrt(d2))); }
1892
+ return d * (k / d2);
1893
+ }
1894
+ fn cell_sum(i: u32, pi: vec4f, c: u32, own: bool) -> vec3f { // one finest cell: exact below nearMax entries, Horvitz-Thompson above (PD-15)
1895
+ let start = cellStart[c];
1896
+ let count = cellStart[c + 1u] - start;
1897
+ var f = vec3f(0.0);
1898
+ if (count <= P.nearMax) {
1899
+ for (var k = start; k < start + count; k = k + 1u) {
1900
+ let jj = sortedIdx[k];
1901
+ if (jj != i) { f = f + pair_force(i, pi, jj, pos[jj]); }
1902
+ }
1903
+ return f;
1904
+ }
1905
+ let base = (c ^ (P.iterationIndex * 0x9E3779B9u)) ^ P.seed; // the per-iteration draw seed (7.16)
1906
+ var sampled = 0u;
1907
+ for (var k = 0u; k < P.nearMax; k = k + 1u) {
1908
+ let jj = sortedIdx[start + (lowbias32(base ^ (k * 0x85EBCA6Bu)) % count)]; // draw k: independent inclusion, with replacement (PD-15)
1909
+ if (jj == i) { continue; }
1910
+ f = f + pair_force(i, pi, jj, pos[jj]);
1911
+ sampled = sampled + 1u;
1912
+ }
1913
+ if (sampled == 0u) { return vec3f(0.0); }
1914
+ let others = select(count, count - 1u, own);
1915
+ return f * (f32(others) / f32(sampled)); // others / sampled over the realised sample (DEP-P4-K)
1916
+ }
1917
+
1918
+ @compute @workgroup_size(WG)
1919
+ fn grid_near_field(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
1920
+ let t = linear_id(wid, lid.x);
1921
+ let valid = t < P.n;
1922
+ var i = 0u;
1923
+ var pi = vec4f(0.0);
1924
+ var f = vec3f(0.0);
1925
+ if (valid) {
1926
+ i = sortedIdx[t]; // sorted order (D24)
1927
+ pi = pos[i];
1928
+ let gf = f32(P.gridMax);
1929
+ let q = (pi.xyz - S.gridMin.xyz) * S.invCellSize;
1930
+ var c0 = vec3<i32>(floor(clamp(q, vec3f(-1.0), vec3f(gf + 1.0))));
1931
+ if (P.dim == 2u) { c0.z = 0; } // 2D: the one z plane
1932
+ let g = i32(P.gridMax);
1933
+ var inside = c0.x >= 0 && c0.x < g && c0.y >= 0 && c0.y < g;
1934
+ if (P.dim == 3u) { inside = inside && c0.z >= 0 && c0.z < g; }
1935
+ if (inside) {
1936
+ let zr = select(0, 1, P.dim == 3u);
1937
+ for (var dz = -zr; dz <= zr; dz = dz + 1) {
1938
+ for (var dy = -1; dy <= 1; dy = dy + 1) {
1939
+ for (var dx = -1; dx <= 1; dx = dx + 1) {
1940
+ let cx = c0.x + dx;
1941
+ let cy = c0.y + dy;
1942
+ let cz = c0.z + dz;
1943
+ if (cx < 0 || cx >= g || cy < 0 || cy >= g || cz < 0 || cz >= g) { continue; }
1944
+ let c = u32(cx) + P.gridMax * (u32(cy) + select(0u, P.gridMax * u32(cz), P.dim == 3u));
1945
+ f = f + cell_sum(i, pi, c, dx == 0 && dy == 0 && dz == 0);
1946
+ }
1947
+ }
1948
+ }
1949
+ } else {
1950
+ var own = grid_cells() + select(0u, 1u, c0.x >= g / 2) + select(0u, 2u, c0.y >= g / 2); // G1's orthant key
1951
+ if (P.dim == 3u) { own = own + select(0u, 4u, c0.z >= g / 2); }
1952
+ for (var o = grid_cells(); o < grid_cells() + select(4u, 8u, P.dim == 3u); o = o + 1u) { // an outside node: every outside pseudo-cell
1953
+ f = f + cell_sum(i, pi, o, o == own);
1954
+ }
1955
+ }
1956
+ }
1957
+ // epilogue (7.9, 7.10): gravity and force += under the guard, the swing / traction reduction outside it (K3's text)
1958
+ var sw = 0.0;
1959
+ var tr = 0.0;
1960
+ if (valid) {
1961
+ f = f + gravity_force(pi);
1962
+ let fnew = load_force(i) + f;
1963
+ store_force(i, fnew);
1964
+ if (SWING_MODE == 1u) { // NetworkX: positions and forces mixed, every node (7.2)
1965
+ sw = pi.w * length(pi.xyz - fnew);
1966
+ tr = 0.5 * pi.w * length(pi.xyz + fnew);
1967
+ } else if (!mask_bit(fixedMask[i >> 5u], i)) { // paper: free nodes only
1968
+ let fold = load_old(i);
1969
+ sw = pi.w * length(fnew - fold);
1970
+ tr = 0.5 * pi.w * length(fnew + fold);
1971
+ }
1972
+ }
1973
+ let tt = wg_reduce_vec4(vec4f(sw, tr, 0.0, 0.0), lid.x, 0u); // uniform control flow: 256 -> 1
1974
+ if (lid.x == 0u) { partials[group_id(wid)].swingTraction = tt.xy; }
1975
+ }
1976
+ `,tx=`
1977
+ var<workgroup> shMax: array<f32, WG>;
1978
+ var<workgroup> shKey: array<u32, WG>;
1979
+ var<workgroup> shSum: array<u32, WG>;
1980
+
1981
+ fn weight_of(a: u32) -> f32 {
1982
+ if (WEIGHTED) { return weights[a]; }
1983
+ return 1.0;
1984
+ }
1985
+ fn scale_of(maxW: f32, d: u32) -> f32 { // 2^s, maxW x d x 2^s in [2^28, 2^30), from exponents alone
1986
+ let em = i32((bitcast<u32>(maxW) >> 23u) & 255u) - 127;
1987
+ let ed = i32(firstLeadingBit(max(d, 1u)));
1988
+ let s = clamp(28 - em - ed, -126, 126);
1989
+ return bitcast<f32>(u32(s + 127) << 23u);
1990
+ }
1991
+ fn inverse_of(scale: f32) -> f32 { // 2^-s, exact
1992
+ let s = i32((bitcast<u32>(scale) >> 23u) & 255u) - 127;
1993
+ return bitcast<f32>(u32(127 - s) << 23u);
1994
+ }
1995
+ fn quantize(w: f32, scale: f32) -> u32 { // nearest integer, halves up; every step exact
1996
+ let x = max(w * scale, 0.0);
1997
+ let i = u32(x);
1998
+ return select(i, i + 1u, x - f32(i) >= 0.5);
1999
+ }
2000
+ fn better(sum: u32, key: u32, bestSum: u32, bestKey0: u32, own: u32) -> bool { // the larger sum; on a tie own key, then lowest
2001
+ return sum > bestSum || (sum == bestSum && bestKey0 != own && (key == own || key < bestKey0));
2002
+ }
2003
+
2004
+ fn row_thread(v: u32) {
2005
+ let lo = rowPtr[v];
2006
+ let hi = rowPtr[v + 1u];
2007
+ var maxW = 0.0;
2008
+ for (var a = lo; a < hi; a = a + 1u) { maxW = max(maxW, weight_of(a)); }
2009
+ let scale = scale_of(maxW, hi - lo);
2010
+ let own = keyIn[v];
2011
+ var bk = INVALID_INDEX;
2012
+ var bs = 0u;
2013
+ for (var a = lo; a < hi; a = a + 1u) {
2014
+ let k = keyIn[colIdx[a]];
2015
+ var seen = false;
2016
+ for (var b = lo; b < a; b = b + 1u) { if (keyIn[colIdx[b]] == k) { seen = true; break; } }
2017
+ if (seen) { continue; } // this key was summed at its first arc
2018
+ var sum = 0u;
2019
+ for (var b = a; b < hi; b = b + 1u) { if (keyIn[colIdx[b]] == k) { sum = sum + quantize(weight_of(b), scale); } }
2020
+ if (better(sum, k, bs, bk, own)) { bk = k; bs = sum; }
2021
+ }
2022
+ bestKey[v] = bk;
2023
+ bestScore[v] = f32(bs) * inverse_of(scale);
2024
+ }
2025
+
2026
+ fn row_hash(g: u32, lid: u32) {
2027
+ let v = rows[P.rowsBase + g];
2028
+ let base = rows[P.basesBase + g];
2029
+ let lo = rowPtr[v];
2030
+ let hi = rowPtr[v + 1u];
2031
+ let cap = GROUP_HASH_LOAD_FACTOR * (hi - lo);
2032
+ var m = 0.0;
2033
+ for (var a = lo + lid; a < hi; a = a + WG) { m = max(m, weight_of(a)); }
2034
+ shMax[lid] = m;
2035
+ workgroupBarrier();
2036
+ for (var s = WG / 2u; s > 0u; s = s / 2u) {
2037
+ if (lid < s) { shMax[lid] = max(shMax[lid], shMax[lid + s]); }
2038
+ workgroupBarrier();
2039
+ }
2040
+ let scale = scale_of(shMax[0], hi - lo);
2041
+ for (var j = lid; j < cap; j = j + WG) { // the region is this workgroup's alone: clear it
2042
+ atomicStore(&hashRegion[base + 2u * j], INVALID_INDEX);
2043
+ atomicStore(&hashRegion[base + 2u * j + 1u], 0u);
2044
+ }
2045
+ storageBarrier();
2046
+ var exhausted = false;
2047
+ for (var a = lo + lid; a < hi; a = a + WG) {
2048
+ let k = keyIn[colIdx[a]];
2049
+ let q = quantize(weight_of(a), scale);
2050
+ var slot = lowbias32(k) % cap;
2051
+ var steps = 0u;
2052
+ loop {
2053
+ if (steps >= cap + 64u) { exhausted = true; break; } // bounded: a spurious compare-exchange failure is legal (WGSL 17.8.5)
2054
+ steps = steps + 1u;
2055
+ let r = atomicCompareExchangeWeak(&hashRegion[base + 2u * slot], INVALID_INDEX, k);
2056
+ if (r.exchanged || r.old_value == k) { atomicAdd(&hashRegion[base + 2u * slot + 1u], q); break; }
2057
+ if (r.old_value == INVALID_INDEX) { continue; } // a spurious failure: the same slot again
2058
+ slot = (slot + 1u) % cap; // linear probing
2059
+ }
2060
+ }
2061
+ if (exhausted) { atomicStore(&hashRegion[0], 1u); }
2062
+ storageBarrier();
2063
+ let own = keyIn[v];
2064
+ var bk = INVALID_INDEX;
2065
+ var bs = 0u;
2066
+ for (var j = lid; j < cap; j = j + WG) {
2067
+ let k = atomicLoad(&hashRegion[base + 2u * j]);
2068
+ if (k != INVALID_INDEX) {
2069
+ let sum = atomicLoad(&hashRegion[base + 2u * j + 1u]);
2070
+ if (better(sum, k, bs, bk, own)) { bk = k; bs = sum; }
2071
+ }
2072
+ }
2073
+ shKey[lid] = bk;
2074
+ shSum[lid] = bs;
2075
+ workgroupBarrier();
2076
+ for (var s = WG / 2u; s > 0u; s = s / 2u) {
2077
+ if (lid < s && better(shSum[lid + s], shKey[lid + s], shSum[lid], shKey[lid], own)) {
2078
+ shKey[lid] = shKey[lid + s];
2079
+ shSum[lid] = shSum[lid + s];
2080
+ }
2081
+ workgroupBarrier();
2082
+ }
2083
+ if (lid == 0u) {
2084
+ bestKey[v] = shKey[0];
2085
+ bestScore[v] = f32(shSum[0]) * inverse_of(scale);
2086
+ }
2087
+ }
2088
+
2089
+ @compute @workgroup_size(WG)
2090
+ fn group_by_key_row(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2091
+ if (TIER == 0u) {
2092
+ let i = linear_id(wid, lid.x);
2093
+ if (i < P.count) { row_thread(rows[P.rowsBase + i]); }
2094
+ return; // TIER is an override: uniform
2095
+ }
2096
+ let g = group_id(wid);
2097
+ if (g >= P.count) { return; } // uniform: the workgroup id and a uniform
2098
+ row_hash(g, lid.x);
2099
+ }
2100
+ `,nx=`
2101
+ @compute @workgroup_size(WG)
2102
+ fn histogram(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2103
+ let i = linear_id(wid, lid.x);
2104
+ if (i >= P.count) { return; } // no barrier follows
2105
+ let k = keys[i];
2106
+ if (k < P.bins) { atomicAdd(&hist[k], 1u); } // order-independent: the count is the same whatever the schedule
2107
+ }
2108
+ `,rx=`
2109
+ @compute @workgroup_size(WG)
2110
+ fn indirect_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
2111
+ if (lid.x != 0u) { return; } // one lane; no barrier follows (3.5 rule 1)
2112
+ let count = counters[P.countIndex];
2113
+ let groups = count / P.wg + select(0u, 1u, count % P.wg != 0u); // ceil(count / wg) without the u32 wrap of (count + wg - 1) above 2^32 - wg: plan1d's rule (5.2) for ANY u32 count
2114
+ var x = groups;
2115
+ var y = 1u;
2116
+ if (groups > MAX_WORKGROUPS_PER_DIM) { // the 2D split; y <= 1,025 for any u32 count
2117
+ x = MAX_WORKGROUPS_PER_DIM;
2118
+ y = (groups + MAX_WORKGROUPS_PER_DIM - 1u) / MAX_WORKGROUPS_PER_DIM;
2119
+ }
2120
+ let base = 4u * P.slot; // 16-byte slots: (x, y, 1, count) (PD-2)
2121
+ args[base] = x;
2122
+ args[base + 1u] = y;
2123
+ args[base + 2u] = 1u;
2124
+ args[base + 3u] = count;
2125
+ }
2126
+ `,ox=`
2127
+ var<workgroup> moved: atomic<u32>;
2128
+
2129
+ @compute @workgroup_size(WG)
2130
+ fn lpa_step(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2131
+ if (lid.x == 0u) { atomicStore(&moved, 0u); }
2132
+ workgroupBarrier();
2133
+ let v = linear_id(wid, lid.x);
2134
+ if (v < P.n) {
2135
+ let cur = labelsIn[v];
2136
+ let best = bestKey[v];
2137
+ var next = cur;
2138
+ if (best != INVALID_INDEX && best != cur) {
2139
+ let down = best < cur;
2140
+ if (down == (P.direction == 0u)) { next = best; } // the alternating direction rule
2141
+ }
2142
+ labelsOut[v] = next;
2143
+ if (next != cur) { atomicAdd(&moved, 1u); }
2144
+ }
2145
+ workgroupBarrier(); // every lane, unconditionally
2146
+ if (lid.x == 0u) {
2147
+ let m = atomicLoad(&moved);
2148
+ if (m > 0u) { atomicAdd(&counters[P.counterIndex], m); } // one atomic per workgroup
2149
+ }
2150
+ }
2151
+ `,sx=`
2152
+ @compute @workgroup_size(WG)
2153
+ fn mst_best(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2154
+ let e = linear_id(wid, lid.x);
2155
+ if (e >= P.count) { return; }
2156
+ let cu = comp[edgeSrc[e]];
2157
+ let cv = comp[edgeDst[e]];
2158
+ if (cu == cv) { return; } // inside one component, or a self-loop
2159
+ var w = 1.0;
2160
+ if (WEIGHTED) { w = edgeWeight[e]; }
2161
+ let k = order_key(w);
2162
+ if (PASS == 0u) {
2163
+ atomicMin(&bestKey[cu], k);
2164
+ atomicMin(&bestKey[cv], k);
2165
+ } else {
2166
+ if (k == atomicLoad(&bestKey[cu])) { atomicMin(&bestEdge[cu], e); }
2167
+ if (k == atomicLoad(&bestKey[cv])) { atomicMin(&bestEdge[cv], e); }
2168
+ }
2169
+ }
2170
+ `,ix=`
2171
+ var<workgroup> added: atomic<u32>;
2172
+
2173
+ @compute @workgroup_size(WG)
2174
+ fn mst_link(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2175
+ if (lid.x == 0u) { atomicStore(&added, 0u); }
2176
+ workgroupBarrier();
2177
+ let c = linear_id(wid, lid.x);
2178
+ if (c < P.count) {
2179
+ let e = bestEdge[c];
2180
+ if (e != INVALID_INDEX) {
2181
+ let a = atomicLoad(&comp[edgeSrc[e]]);
2182
+ let b = atomicLoad(&comp[edgeDst[e]]);
2183
+ let other = select(a, b, a == c);
2184
+ let keep = bestEdge[other] == e && c <= other; // the lower root of a two-cycle stays
2185
+ if (!keep) { atomicStore(&comp[c], other); }
2186
+ if (!keep) { treeEdge[c] = e; atomicAdd(&added, 1u); }
2187
+ }
2188
+ }
2189
+ workgroupBarrier(); // every lane, unconditionally
2190
+ if (lid.x == 0u) {
2191
+ let k = atomicLoad(&added);
2192
+ if (k > 0u) { atomicAdd(&counters[P.counterIndex], k); } // one atomic per workgroup
2193
+ }
2194
+ }
2195
+ `,ax=`
2196
+ @compute @workgroup_size(WG)
2197
+ fn orient_flags(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2198
+ let a = linear_id(wid, lid.x);
2199
+ if (a >= P.count) { return; } // no barrier follows
2200
+ let u = src[a];
2201
+ let v = colIdx[a];
2202
+ let du = rowPtr[u + 1u] - rowPtr[u];
2203
+ let dv = rowPtr[v + 1u] - rowPtr[v];
2204
+ let keep = dv > du || (dv == du && v > u); // (degree, id) of the target above the source's
2205
+ flags[a] = select(0u, 1u, keep);
2206
+ }
2207
+ `,cx=`
2208
+ @compute @workgroup_size(WG)
2209
+ fn pr_finalize(@builtin(local_invocation_id) lid: vec3<u32>) {
2210
+ var d = 0.0;
2211
+ var e = 0.0;
2212
+ var m = 0.0;
2213
+ for (var g = lid.x; g < P.groups; g = g + WG) {
2214
+ d = d + partials[1u + g].danglingMass;
2215
+ e = e + partials[1u + g].delta;
2216
+ m = m + partials[1u + g].norm;
2217
+ }
2218
+ let folded = wg_reduce_vec4(vec4f(d, e, m, 0.0), lid.x, 0u);
2219
+ if (lid.x == 0u) {
2220
+ partials[0].danglingMass = folded.x;
2221
+ partials[0].delta = folded.y;
2222
+ var norm = folded.z;
2223
+ if (NORM_MODE == 2u) { norm = sqrt(max(0.0, folded.z)); }
2224
+ partials[0].norm = norm;
2225
+ partials[0].iteration = P.iteration;
2226
+ let unset = partials[0].firstConverged == U32_MAX;
2227
+ if (P.trackConvergence == 1u && P.iteration >= 2u && folded.y < P.convergeThreshold && unset) {
2228
+ partials[0].firstConverged = P.iteration - 1u;
2229
+ }
2230
+ }
2231
+ }
2232
+ `,lx=`
2233
+ @compute @workgroup_size(WG)
2234
+ fn pr_scale(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2235
+ let u = linear_id(wid, lid.x);
2236
+ let inRange = u < P.n;
2237
+ var x = 0.0;
2238
+ var prev = 0.0;
2239
+ if (inRange) { x = rankIn[u]; prev = rankPrev[u]; }
2240
+ var dangling = 0.0;
2241
+ var delta = 0.0;
2242
+ var normTerm = 0.0;
2243
+ if (inRange) {
2244
+ delta = abs(x - prev);
2245
+ if (NORM_MODE == 0u) {
2246
+ let divisor = outWeightSum[u];
2247
+ if (divisor <= 0.0) { dangling = x; xNorm[u] = 0.0; } else { xNorm[u] = x / divisor; }
2248
+ }
2249
+ if (NORM_MODE == 1u) { normTerm = abs(x); }
2250
+ if (NORM_MODE == 2u) { normTerm = x * x; }
2251
+ if (NORM_MODE == 3u) {
2252
+ var scale = partials[0].norm;
2253
+ if (scale <= 0.0) { scale = 1.0; }
2254
+ xNorm[u] = x / scale;
2255
+ }
2256
+ if (NORM_MODE == 4u) { xNorm[u] = x; }
2257
+ }
2258
+ let folded = wg_reduce_vec4(vec4f(dangling, delta, normTerm, 0.0), lid.x, 0u);
2259
+ if (lid.x == 0u) {
2260
+ let slot = 1u + group_id(wid);
2261
+ partials[slot].danglingMass = folded.x;
2262
+ partials[slot].delta = folded.y;
2263
+ partials[slot].norm = folded.z;
2264
+ }
2265
+ }
2266
+ `,ux=`
2267
+ var<workgroup> local: array<atomic<u32>, RADIX_BINS>;
2268
+
2269
+ @compute @workgroup_size(WG)
2270
+ fn radix_hist(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2271
+ for (var b = lid.x; b < RADIX_BINS; b = b + WG) { atomicStore(&local[b], 0u); }
2272
+ workgroupBarrier();
2273
+ let g = group_id(wid);
2274
+ let i = g * WG + lid.x;
2275
+ if (i < P.count) {
2276
+ let d = (keys[i] >> P.shift) & RADIX_DIGIT_MASK; // the pass's digit
2277
+ atomicAdd(&local[d], 1u);
2278
+ }
2279
+ workgroupBarrier();
2280
+ // Above MAX_1D_ITEMS plan1d pads the 2D grid to x * y >= P.groups workgroups; a padding workgroup (g >= P.groups)
2281
+ // holds an all-zero table and its digit-major slot b * P.groups + g is digit b + 1's slot of a REAL group, so it
2282
+ // must not store. Uniform per workgroup, no barrier inside. Every test size fits 1D (the ladder tops at 2^22); no
2283
+ // case reaches this branch, so the guard is proved by reading, not by a run.
2284
+ if (g < P.groups) {
2285
+ for (var b = lid.x; b < RADIX_BINS; b = b + WG) { hist[b * P.groups + g] = atomicLoad(&local[b]); } // digit-major
2286
+ }
2287
+ }
2288
+ `,dx=`
2289
+ var<workgroup> rank: array<u32, WG>;
2290
+ var<workgroup> cnt: array<u32, RADIX_BINS>;
2291
+
2292
+ @compute @workgroup_size(WG)
2293
+ fn radix_scatter(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2294
+ for (var b = lid.x; b < RADIX_BINS; b = b + WG) { cnt[b] = 0u; }
2295
+ let g = group_id(wid);
2296
+ let i = g * WG + lid.x;
2297
+ var key = 0u;
2298
+ var d = 0u;
2299
+ if (i < P.count) {
2300
+ key = keys[i];
2301
+ d = (key >> P.shift) & RADIX_DIGIT_MASK;
2302
+ }
2303
+ workgroupBarrier();
2304
+ if (lid.x == 0u) { // serial stable ranking (PD-5)
2305
+ let last = min(WG, P.count - g * WG);
2306
+ for (var s = 0u; s < last; s = s + 1u) {
2307
+ let ds = (keys[g * WG + s] >> P.shift) & RADIX_DIGIT_MASK;
2308
+ rank[s] = cnt[ds];
2309
+ cnt[ds] = cnt[ds] + 1u;
2310
+ }
2311
+ }
2312
+ workgroupBarrier();
2313
+ if (i < P.count) {
2314
+ let dst = offsets[d * P.groups + g] + rank[lid.x];
2315
+ keysOut[dst] = key;
2316
+ valsOut[dst] = vals[i];
2317
+ }
2318
+ }
2319
+ `,fx=`
2320
+ // DTYPE 0 = f32, 1 = u32, 2 = vec4f (4 words per element); OP 0 = sum, 1 = min, 2 = max; FINAL = the one-workgroup level
2321
+ fn identity_f() -> f32 { if (OP == 1u) { return F32_MAX; } if (OP == 2u) { return -F32_MAX; } return 0.0; }
2322
+ fn identity_u() -> u32 { if (OP == 1u) { return U32_MAX; } return 0u; } // U32_MAX from the prelude: the literal is forbidden in bodies (4.1)
2323
+ fn comb_f(a: f32, b: f32) -> f32 { if (OP == 1u) { return min(a, b); } if (OP == 2u) { return max(a, b); } return a + b; }
2324
+ fn comb_u(a: u32, b: u32) -> u32 { if (OP == 1u) { return min(a, b); } if (OP == 2u) { return max(a, b); } return a + b; }
2325
+ fn comb_v(a: vec4f, b: vec4f) -> vec4f { if (OP == 1u) { return min(a, b); } if (OP == 2u) { return max(a, b); } return a + b; }
2326
+ fn load_f(i: u32) -> f32 { return bitcast<f32>(src[i]); }
2327
+ fn load_v(i: u32) -> vec4f {
2328
+ return vec4f(bitcast<f32>(src[4u * i]), bitcast<f32>(src[4u * i + 1u]), bitcast<f32>(src[4u * i + 2u]), bitcast<f32>(src[4u * i + 3u]));
2329
+ }
2330
+ fn store_f(i: u32, v: f32) { out[i] = bitcast<u32>(v); }
2331
+ fn store_v(i: u32, v: vec4f) {
2332
+ out[4u * i] = bitcast<u32>(v.x);
2333
+ out[4u * i + 1u] = bitcast<u32>(v.y);
2334
+ out[4u * i + 2u] = bitcast<u32>(v.z);
2335
+ out[4u * i + 3u] = bitcast<u32>(v.w);
2336
+ }
2337
+
2338
+ @compute @workgroup_size(WG)
2339
+ fn reduce(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2340
+ var accF = identity_f();
2341
+ var accU = identity_u();
2342
+ var accV = vec4f(identity_f());
2343
+ if (FINAL) {
2344
+ for (var i = lid.x; i < P.count; i = i + WG) { // sequential per lane in index order: deterministic
2345
+ if (DTYPE == 0u) { accF = comb_f(accF, load_f(i)); }
2346
+ else if (DTYPE == 1u) { accU = comb_u(accU, src[i]); }
2347
+ else { accV = comb_v(accV, load_v(i)); }
2348
+ }
2349
+ } else {
2350
+ let i = linear_id(wid, lid.x);
2351
+ if (i < P.count) {
2352
+ if (DTYPE == 0u) { accF = load_f(i); }
2353
+ else if (DTYPE == 1u) { accU = src[i]; }
2354
+ else { accV = load_v(i); }
2355
+ }
2356
+ }
2357
+ // uniform control flow: the workgroup reduction of the selected dtype (DTYPE is a pipeline constant, so the branch is uniform)
2358
+ var tF = 0.0;
2359
+ var tU = 0u;
2360
+ var tV = vec4f(0.0);
2361
+ if (DTYPE == 0u) { tF = wg_reduce_f32(accF, lid.x, OP); }
2362
+ else if (DTYPE == 1u) { tU = wg_reduce_u32(accU, lid.x, OP); }
2363
+ else { tV = wg_reduce_vec4(accV, lid.x, OP); }
2364
+ if (lid.x == 0u) {
2365
+ let g = select(group_id(wid), 0u, FINAL);
2366
+ let o = P.outOffset + g;
2367
+ if (DTYPE == 0u) { store_f(o, tF); }
2368
+ else if (DTYPE == 1u) { out[o] = tU; }
2369
+ else { store_v(o, tV); }
2370
+ }
2371
+ }
2372
+ `,hx=`
2373
+ @compute @workgroup_size(WG)
2374
+ fn run_flags(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2375
+ let i = linear_id(wid, lid.x);
2376
+ if (i >= P.count) { return; } // no barrier follows
2377
+ let a = keysA[i];
2378
+ var first = a != INVALID_INDEX; // a dropped arc never opens a run
2379
+ if (i > 0u) { first = first && (a != keysA[i - 1u] || keysB[i] != keysB[i - 1u]); }
2380
+ flags[i] = select(0u, 1u, first);
2381
+ }
2382
+ `,gx=`
2383
+ @compute @workgroup_size(WG)
2384
+ fn scan_add(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2385
+ let g = group_id(wid);
2386
+ let i = g * WG + lid.x;
2387
+ if (i >= P.count) { return; } // no barrier follows
2388
+ out[i] = out[i] + blockOffsets[g];
2389
+ }
2390
+ `,wx=`
2391
+ var<workgroup> sh: array<u32, WG>;
2392
+
2393
+ @compute @workgroup_size(WG)
2394
+ fn scan_block(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2395
+ let g = group_id(wid);
2396
+ let i = g * WG + lid.x;
2397
+ var v = 0u;
2398
+ if (i < P.count) { v = src[i]; }
2399
+ sh[lid.x] = v;
2400
+ workgroupBarrier();
2401
+ for (var s = 1u; s < WG; s = s * 2u) { // Hillis-Steele inclusive scan; uniform: every lane runs every round
2402
+ var t = 0u;
2403
+ if (lid.x >= s) { t = sh[lid.x - s]; }
2404
+ workgroupBarrier();
2405
+ sh[lid.x] = sh[lid.x] + t;
2406
+ workgroupBarrier();
2407
+ }
2408
+ let inclusive = sh[lid.x];
2409
+ if (i < P.count) { out[i] = inclusive - v; } // exclusive = inclusive - own value
2410
+ if (lid.x == WG - 1u) { blockSums[g] = inclusive; } // the block total (the last lane's inclusive sum)
2411
+ }
2412
+ `,px=`
2413
+ fn identity() -> f32 { if (OP == 1u) { return F32_MAX; } if (OP == 2u) { return -F32_MAX; } return 0.0; }
2414
+ fn comb(a: f32, b: f32) -> f32 { if (OP == 1u) { return min(a, b); } if (OP == 2u) { return max(a, b); } return a + b; }
2415
+ fn row_node(row: u32) -> u32 { return select(row, perm[row], USE_PERM); }
2416
+ fn row_fold(i: u32, lane: u32, step: u32) -> f32 { // the arcs of row i this lane walks inside the bound window [P.arcBase, P.arcEnd)
2417
+ let row = i; // the CSR row the VALUE snippet may name (the node index, under USE_PERM too)
2418
+ let a0 = max(rowPtr[i], P.arcBase);
2419
+ let a1 = min(rowPtr[i + 1u], P.arcEnd);
2420
+ var acc = identity();
2421
+ for (var arc = a0 + lane; arc < a1; arc = arc + step) {
2422
+ let nbr = colIdx[arc - P.arcBase]; // the neighbour index (\`target\` is a WGSL reserved word)
2423
+ var weight = 1.0;
2424
+ if (HAS_WEIGHTS) { weight = weights[arc - P.arcBase]; }
2425
+ var v = 0.0;
2426
+ //@@VALUE@@
2427
+ acc = comb(acc, v);
2428
+ }
2429
+ return acc;
2430
+ }
2431
+ fn row_fold_dense(i: u32) -> f32 { // TIER 0's stride-one twin of row_fold (see the header)
2432
+ let row = i; // the CSR row the VALUE snippet may name (as in row_fold)
2433
+ let lo = max(rowPtr[i], P.arcBase);
2434
+ let hi = min(rowPtr[i + 1u], P.arcEnd);
2435
+ var acc = identity();
2436
+ for (var left = select(0u, hi - lo, hi > lo); left > 0u; left = left - 1u) { // counts DOWN (see the header)
2437
+ let arc = hi - left; // lo, lo + 1, ..., hi - 1
2438
+ let k = arc - P.arcBase; // the window-local index; this walk is contiguous
2439
+ let nbr = colIdx[k];
2440
+ var weight = 1.0;
2441
+ if (HAS_WEIGHTS) { weight = weights[k]; }
2442
+ var v = 0.0;
2443
+ //@@VALUE@@
2444
+ acc = comb(acc, v);
2445
+ }
2446
+ return acc;
2447
+ }
2448
+ fn finish(i: u32, acc: f32) { out[i] = select(acc, comb(out[i], acc), P.accumulate == 1u); }
2449
+ fn tier0(wid: vec3<u32>, lane: u32) { // TIER 0: one row per thread over [P.start, P.end); no barrier, so the early return is legal (3.5 rule 1)
2450
+ let row = linear_id(wid, lane) + P.start;
2451
+ if (row >= P.end) { return; }
2452
+ let i = row_node(row);
2453
+ finish(i, row_fold_dense(i));
2454
+ }
2455
+
2456
+ var<workgroup> sh: array<f32, WG>;
2457
+
2458
+ fn tiered(wid: vec3<u32>, lid: u32) { // TIER 1: 32 lanes per row, WG / 32 rows per workgroup; TIER 2: WG lanes per row (PD-6)
2459
+ let g = group_id(wid);
2460
+ var row = P.start + g;
2461
+ var lane = lid;
2462
+ var step = WG;
2463
+ if (TIER == 1u) { row = P.start + g * (WG / 32u) + lid / 32u; lane = lid % 32u; step = 32u; }
2464
+ let valid = row < P.end;
2465
+ var i = 0u;
2466
+ var acc = identity();
2467
+ if (valid) { i = row_node(row); acc = row_fold(i, lane, step); }
2468
+ if (TIER == 1u) {
2469
+ sh[lid] = acc;
2470
+ workgroupBarrier();
2471
+ for (var s = 16u; s >= 1u; s = s / 2u) { // the five-step tree over each 32-lane group; every lane runs every step
2472
+ var t = identity();
2473
+ if (lane < s) { t = sh[lid + s]; }
2474
+ workgroupBarrier();
2475
+ sh[lid] = comb(sh[lid], t);
2476
+ workgroupBarrier();
2477
+ }
2478
+ if (valid && lane == 0u) { finish(i, sh[lid]); }
2479
+ }
2480
+ if (TIER == 2u) {
2481
+ let t = wg_reduce_f32(acc, lid, OP); // the workgroup tree of the prelude (subgroup variant when available)
2482
+ if (valid && lid == 0u) { finish(i, t); }
2483
+ }
2484
+ }
2485
+
2486
+ @compute @workgroup_size(WG)
2487
+ fn segmented_reduce(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2488
+ if (TIER == 0u) { tier0(wid, lid.x); } else { tiered(wid, lid.x); }
2489
+ }
2490
+ `,mx=`
2491
+ fn row_node(row: u32) -> u32 { return select(row, perm[row], USE_PERM); }
2492
+ fn row_sum(v: u32, lane: u32, step: u32) -> f32 { // this lane's arcs of row v inside the bound window, the two-level 64-term fold of the header
2493
+ let a0 = max(rowPtr[v], P.arcBase);
2494
+ let a1 = min(rowPtr[v + 1u], P.arcEnd);
2495
+ var acc = 0.0;
2496
+ var chunk = 0.0;
2497
+ var inChunk = 0u;
2498
+ for (var arc = a0 + lane; arc < a1; arc = arc + step) {
2499
+ let nbr = colIdx[arc - P.arcBase]; // \`target\` is a WGSL reserved word (spec 16.2)
2500
+ var weight = 1.0;
2501
+ if (HAS_WEIGHTS) { weight = weights[arc - P.arcBase]; }
2502
+ // two-level sum: 64 terms into chunk, chunk into acc (see the header; no compensation, no select)
2503
+ chunk = chunk + (weight * xNorm[nbr]);
2504
+ inChunk = inChunk + 1u;
2505
+ if (inChunk == 64u) {
2506
+ acc = acc + chunk;
2507
+ chunk = 0.0;
2508
+ inChunk = 0u;
2509
+ }
2510
+ }
2511
+ acc = acc + chunk;
2512
+ return acc;
2513
+ }
2514
+ fn row_sum_dense(v: u32) -> f32 { // TIER 0's stride-one twin of row_sum (see the header)
2515
+ let lo = max(rowPtr[v], P.arcBase);
2516
+ let hi = min(rowPtr[v + 1u], P.arcEnd);
2517
+ var acc = 0.0;
2518
+ var chunk = 0.0;
2519
+ var inChunk = 0u;
2520
+ for (var left = select(0u, hi - lo, hi > lo); left > 0u; left = left - 1u) { // counts DOWN (see the header)
2521
+ let arc = hi - left; // lo, lo + 1, ..., hi - 1
2522
+ let k = arc - P.arcBase; // the window-local index; this walk is contiguous
2523
+ let nbr = colIdx[k]; // \`target\` is a WGSL reserved word (spec 16.2)
2524
+ var weight = 1.0;
2525
+ if (HAS_WEIGHTS) { weight = weights[k]; }
2526
+ // two-level sum: 64 terms into chunk, chunk into acc (see the header; no compensation, no select)
2527
+ chunk = chunk + (weight * xNorm[nbr]);
2528
+ inChunk = inChunk + 1u;
2529
+ if (inChunk == 64u) {
2530
+ acc = acc + chunk;
2531
+ chunk = 0.0;
2532
+ inChunk = 0u;
2533
+ }
2534
+ }
2535
+ acc = acc + chunk;
2536
+ return acc;
2537
+ }
2538
+ fn finish(v: u32, acc: f32) {
2539
+ var dangling = 0.0;
2540
+ if (USE_DANGLING) { dangling = partials[0].danglingMass; }
2541
+ var pv = P.uniformP;
2542
+ if (HAS_PERSONALIZATION) { pv = personalization[v]; }
2543
+ rankOut[v] = (P.beta * pv) + (P.alpha * (acc + (dangling * pv)));
2544
+ }
2545
+ fn tier0(wid: vec3<u32>, lane: u32) { // TIER 0: grid-stride over the rows [P.start, P.n); no barrier
2546
+ for (var row = linear_id(wid, lane) + P.start; row < P.n; row = row + P.stride) {
2547
+ let v = row_node(row);
2548
+ finish(v, row_sum_dense(v));
2549
+ }
2550
+ }
2551
+
2552
+ var<workgroup> sh: array<f32, WG>;
2553
+
2554
+ fn tiered(wid: vec3<u32>, lid: u32) { // TIER 1: 32 lanes per row; TIER 2: WG lanes per row; rows [P.start, P.n) (PD-6)
2555
+ let g = group_id(wid);
2556
+ var row = P.start + g;
2557
+ var lane = lid;
2558
+ var step = WG;
2559
+ if (TIER == 1u) { row = P.start + g * (WG / 32u) + lid / 32u; lane = lid % 32u; step = 32u; }
2560
+ let valid = row < P.n;
2561
+ var v = 0u;
2562
+ var acc = 0.0;
2563
+ if (valid) { v = row_node(row); acc = row_sum(v, lane, step); }
2564
+ if (TIER == 1u) {
2565
+ sh[lid] = acc;
2566
+ workgroupBarrier();
2567
+ for (var s = 16u; s >= 1u; s = s / 2u) { // the five-step tree over each 32-lane group; every lane runs every step
2568
+ var t = 0.0;
2569
+ if (lane < s) { t = sh[lid + s]; }
2570
+ workgroupBarrier();
2571
+ sh[lid] = sh[lid] + t;
2572
+ workgroupBarrier();
2573
+ }
2574
+ if (valid && lane == 0u) { finish(v, sh[lid]); }
2575
+ }
2576
+ if (TIER == 2u) {
2577
+ let t = wg_reduce_f32(acc, lid, 0u);
2578
+ if (valid && lid == 0u) { finish(v, t); }
2579
+ }
2580
+ }
2581
+
2582
+ @compute @workgroup_size(WG)
2583
+ fn spmv_pull(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2584
+ if (TIER == 0u) { tier0(wid, lid.x); } else { tiered(wid, lid.x); }
2585
+ }
2586
+ `,yx=`
2587
+ @compute @workgroup_size(WG)
2588
+ fn sssp_pred(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2589
+ let first = linear_id(wid, lid.x);
2590
+ let hb = ((P.n + 63u) / 64u) * 64u; // MODE 0 only: hops[v] is pred[hb + v]; pred[2 hb] is the changed word, pred[2 hb + 1] the orphan word (PD-27)
2591
+ if (P.role == 1u && P.iteration != 0u && atomicLoad(&pred[2u * hb]) < P.iteration) { return; } // the previous hop pass changed nothing: converged (no barrier anywhere, so the early return is legal)
2592
+ for (var u = first; u < P.n; u = u + P.stride) { // grid-stride over the rows (planGridStride(n)); no barrier anywhere
2593
+ let du = dist[u];
2594
+ var unreached = false;
2595
+ if (MODE == 1u) { unreached = du == INVALID_INDEX; } else { unreached = du == F32_INF_BITS; }
2596
+ if (unreached) { continue; }
2597
+ var hu = 0u; // u's hop count (MODE 0, roles 1 and 2)
2598
+ if (MODE == 0u && P.role != 0u) {
2599
+ hu = atomicLoad(&pred[hb + u]);
2600
+ if (hu == INVALID_INDEX) { // the key has not reached u yet
2601
+ if (P.role == 2u && u != P.source) { atomicAdd(&pred[2u * hb + 1u], 1u); } // an orphan: only bellmanFord can make one (P8-T10 Step 3)
2602
+ continue;
2603
+ }
2604
+ }
2605
+ let end = min(rowPtr[u + 1u], P.arcEnd);
2606
+ for (var a = max(rowPtr[u], P.arcBase); a < end; a = a + 1u) {
2607
+ let v = colIdx[a - P.arcBase];
2608
+ if (v == P.source) { continue; } // the source keeps INVALID_INDEX whatever attains it (a zero-weight arc could)
2609
+ let dv = dist[v];
2610
+ var tight = false; // the arc explains dist[v]
2611
+ var below = false; // and its source sits at a strictly smaller distance
2612
+ if (MODE == 1u) {
2613
+ tight = (du + 1u) == dv; // depth mode: BFS parent, one depth down
2614
+ } else {
2615
+ let w = select(1.0, weights[a - P.arcBase], HAS_WEIGHTS);
2616
+ tight = (dv != F32_INF_BITS) && (bitcast<u32>(bitcast<f32>(du) + w) == dv); // one f32 add, compared as the bit pattern PD-9 stores; never into an unreached v (an overflowed sum is +Inf too)
2617
+ below = bitcast<f32>(du) < bitcast<f32>(dv);
2618
+ }
2619
+ if (!tight) { continue; }
2620
+ var admit = false; // this arc is one key step below v
2621
+ if (MODE == 1u) {
2622
+ admit = true;
2623
+ } else if (P.role == 0u) { // the roots pass (the plateau rule only; bellmanFord seeds the source alone)
2624
+ if (P.mode == 0u && below) { atomicMin(&pred[hb + v], 0u); }
2625
+ } else if (P.role == 1u) { // a hop pass: one hop along a plateau arc (mode 0) or along any tight arc (mode 1)
2626
+ if (P.mode == 1u || du == dv) {
2627
+ let old = atomicMin(&pred[hb + v], hu + 1u);
2628
+ if (hu + 1u < old) { atomicMax(&pred[2u * hb], P.iteration + 1u); } // this pass changed something
2629
+ }
2630
+ } else { // the predecessor pass: the smallest tight arc one key step below v
2631
+ let hv = atomicLoad(&pred[hb + v]);
2632
+ if (P.mode == 1u) { admit = hu + 1u == hv; } else if (hv == 0u) { admit = below; } else { admit = (du == dv) && (hu + 1u == hv); }
2633
+ }
2634
+ if (admit) { atomicMin(&pred[v], select(a, u, P.predKind == 1u)); }
2635
+ }
2636
+ }
2637
+ }
2638
+ `,bx=`
2639
+ @compute @workgroup_size(WG)
2640
+ fn sssp_relax(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2641
+ let first = linear_id(wid, lid.x);
2642
+ let mine = select(5u, 6u, P.role == 1u); // the path word role 2 wrote: 5 a near round, 6 a far pass-through
2643
+ let chosen = atomicLoad(&counters[24]) == mine; // the other role's dispatch of the round is a no-op
2644
+ let count = select(0u, min(atomicLoad(&counters[select(0u, 20u, P.role == 1u)]), P.n), chosen); // the deduped near or far pile
2645
+ let threshold = bitcast<f32>(atomicLoad(&counters[22]));
2646
+ let cutoff = bitcast<f32>(P.cutoffBits);
2647
+ for (var i = first; i < count; i = i + P.stride) { // no barrier anywhere: the loops may be per lane
2648
+ let u = queueIn[i];
2649
+ let du = bitcast<f32>(atomicLoad(&dist[u]));
2650
+ if (P.role == 1u) { // the pass-through (PD-20): re-bucket a far entry
2651
+ if (du < bitcast<f32>(atomicLoad(&counters[4]))) { continue; } // below the previous threshold: relaxed in an earlier bucket
2652
+ if (du < threshold) {
2653
+ let q = atomicAdd(&counters[1], 1u);
2654
+ if (q < P.edgeCapacity) { queueOut[q] = u; }
2655
+ } else {
2656
+ let q = atomicAdd(&counters[21], 1u);
2657
+ if (q < P.edgeCapacity) { queueOut[P.edgeCapacity + q] = u; }
2658
+ }
2659
+ continue;
2660
+ }
2661
+ let end = rowPtr[u + 1u];
2662
+ for (var a = rowPtr[u]; a < end; a = a + 1u) { // the whole row: never windowed (DEP-P8-E)
2663
+ let v = colIdx[a];
2664
+ let nd = du + select(1.0, weights[a], HAS_WEIGHTS); // ONE f32 add (PD-9)
2665
+ if (nd > cutoff) { continue; } // SsspOptions.cutoff: the CPU port's dv <= cutoff
2666
+ let bits = bitcast<u32>(nd);
2667
+ let old = atomicMin(&dist[v], bits); // exact on non-negative floats
2668
+ if (bits < old) { // this lane improved v, so it owns the append
2669
+ if (nd < threshold) {
2670
+ let q = atomicAdd(&counters[1], 1u);
2671
+ if (q < P.edgeCapacity) { queueOut[q] = v; }
2672
+ } else {
2673
+ let q = atomicAdd(&counters[21], 1u);
2674
+ if (q < P.edgeCapacity) { queueOut[P.edgeCapacity + q] = v; }
2675
+ }
2676
+ }
2677
+ }
2678
+ }
2679
+ }
2680
+ `,vx=`
2681
+ fn contains(lo0: u32, hi0: u32, x: u32) -> bool { // binary search of x in colIdx[lo0, hi0), sorted ascending
2682
+ var lo = lo0;
2683
+ var hi = hi0;
2684
+ loop {
2685
+ if (lo >= hi) { break; }
2686
+ let mid = lo + (hi - lo) / 2u;
2687
+ let y = colIdx[mid];
2688
+ if (y == x) { return true; }
2689
+ if (y < x) { lo = mid + 1u; } else { hi = mid; }
2690
+ }
2691
+ return false;
2692
+ }
2693
+
2694
+ @compute @workgroup_size(WG)
2695
+ fn tri_intersect(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2696
+ let a = linear_id(wid, lid.x);
2697
+ if (a >= P.count) { return; } // no barrier follows
2698
+ let u = src[a];
2699
+ let v = colIdx[a];
2700
+ let uLo = rowPtr[u];
2701
+ let uHi = rowPtr[u + 1u];
2702
+ let vLo = rowPtr[v];
2703
+ let vHi = rowPtr[v + 1u];
2704
+ let du = uHi - uLo;
2705
+ let dv = vHi - vLo;
2706
+ var search = SEARCH == 2u;
2707
+ if (SEARCH == 0u) { search = du / TRIANGLE_BINARY_SEARCH_RATIO > dv || dv / TRIANGLE_BINARY_SEARCH_RATIO > du; }
2708
+ var found = 0u;
2709
+ if (search) {
2710
+ var sLo = uLo;
2711
+ var sHi = uHi;
2712
+ var lLo = vLo;
2713
+ var lHi = vHi;
2714
+ if (du > dv) { sLo = vLo; sHi = vHi; lLo = uLo; lHi = uHi; }
2715
+ for (var k = sLo; k < sHi; k = k + 1u) {
2716
+ let w = colIdx[k];
2717
+ if (contains(lLo, lHi, w)) { atomicAdd(&counts[w], 1u); found = found + 1u; }
2718
+ }
2719
+ } else {
2720
+ var i = uLo;
2721
+ var j = vLo;
2722
+ loop {
2723
+ if (i >= uHi || j >= vHi) { break; }
2724
+ let x = colIdx[i];
2725
+ let y = colIdx[j];
2726
+ if (x == y) { atomicAdd(&counts[x], 1u); found = found + 1u; i = i + 1u; j = j + 1u; }
2727
+ else if (x < y) { i = i + 1u; }
2728
+ else { j = j + 1u; }
2729
+ }
2730
+ }
2731
+ if (found > 0u) { atomicAdd(&counts[u], found); atomicAdd(&counts[v], found); }
2732
+ }
2733
+ `,Ax=`
2734
+ @compute @workgroup_size(WG)
2735
+ fn wcc_compress(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2736
+ let first = linear_id(wid, lid.x);
2737
+ for (var v = first; v < P.items; v = v + P.stride) {
2738
+ var root = atomicLoad(&comp[v]);
2739
+ var steps = 0u;
2740
+ loop {
2741
+ let parent = atomicLoad(&comp[root]);
2742
+ if (parent == root) { break; }
2743
+ if (steps >= P.maxSteps) { break; }
2744
+ steps = steps + 1u;
2745
+ root = parent;
2746
+ }
2747
+ atomicStore(&comp[v], root);
2748
+ }
2749
+ }
2750
+ `,Ex=`
2751
+ fn link_pair(a: u32, b: u32) {
2752
+ var p1 = atomicLoad(&comp[a]);
2753
+ var p2 = atomicLoad(&comp[b]);
2754
+ var steps = 0u;
2755
+ loop {
2756
+ if (p1 == p2) { break; }
2757
+ if (steps >= P.maxSteps) { atomicStore(&comp[P.flagIndex], 1u); break; }
2758
+ steps = steps + 1u;
2759
+ let hi = max(p1, p2);
2760
+ let lo = min(p1, p2);
2761
+ let pHigh = atomicLoad(&comp[hi]);
2762
+ if (pHigh == lo) { break; }
2763
+ if (pHigh == hi) {
2764
+ let swapped = atomicCompareExchangeWeak(&comp[hi], hi, lo);
2765
+ if (swapped.exchanged) { atomicStore(&comp[P.flagIndex], 1u); break; }
2766
+ }
2767
+ p1 = atomicLoad(&comp[atomicLoad(&comp[hi])]);
2768
+ p2 = atomicLoad(&comp[lo]);
2769
+ }
2770
+ }
2771
+
2772
+ @compute @workgroup_size(WG)
2773
+ fn wcc_link_edges(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2774
+ let first = linear_id(wid, lid.x);
2775
+ for (var e = first; e < P.items; e = e + P.stride) {
2776
+ let u = edgeSrc[e];
2777
+ let v = edgeDst[e];
2778
+ if (u == v) { continue; }
2779
+ if (atomicLoad(&comp[u]) == P.giant && atomicLoad(&comp[v]) == P.giant) { continue; }
2780
+ link_pair(u, v);
2781
+ }
2782
+ }
2783
+ `,_x=`
2784
+ fn link_pair(a: u32, b: u32) {
2785
+ var p1 = atomicLoad(&comp[a]);
2786
+ var p2 = atomicLoad(&comp[b]);
2787
+ var steps = 0u;
2788
+ loop {
2789
+ if (p1 == p2) { break; }
2790
+ if (steps >= P.maxSteps) { atomicStore(&comp[P.flagIndex], 1u); break; }
2791
+ steps = steps + 1u;
2792
+ let hi = max(p1, p2);
2793
+ let lo = min(p1, p2);
2794
+ let pHigh = atomicLoad(&comp[hi]);
2795
+ if (pHigh == lo) { break; }
2796
+ if (pHigh == hi) {
2797
+ let swapped = atomicCompareExchangeWeak(&comp[hi], hi, lo);
2798
+ if (swapped.exchanged) { atomicStore(&comp[P.flagIndex], 1u); break; }
2799
+ }
2800
+ p1 = atomicLoad(&comp[atomicLoad(&comp[hi])]);
2801
+ p2 = atomicLoad(&comp[lo]);
2802
+ }
2803
+ }
2804
+
2805
+ @compute @workgroup_size(WG)
2806
+ fn wcc_link_sample(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2807
+ let first = linear_id(wid, lid.x);
2808
+ for (var row = first; row < P.items; row = row + P.stride) {
2809
+ let v = select(row, perm[row], USE_PERM);
2810
+ let a0 = rowPtr[v];
2811
+ let a1 = rowPtr[v + 1u];
2812
+ if (a0 + P.r < a1) {
2813
+ link_pair(v, colIdx[a0 + P.r]);
2814
+ }
2815
+ }
2816
+ }
2817
+ `,Ix=`
2818
+ @compute @workgroup_size(WG)
2819
+ fn wcc_sample(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
2820
+ let i = linear_id(wid, lid.x);
2821
+ if (i >= P.items) { return; }
2822
+ let v = lowbias32(i + P.r) % P.n;
2823
+ hist[i] = atomicLoad(&comp[v]);
2824
+ }
2825
+ `,vl=Ie.define("RangeParams",[["start","u32"],["end","u32"],["arcBase","u32"],["arcEnd","u32"],["accumulate","u32"],["n","u32"],["pad0","u32"],["pad1","u32"]]),kx=Ie.define("ReduceParams",[["count","u32"],["outOffset","u32"],["level","u32"],["pad0","u32"]]),Ze=Ie.define("FillParams",[["count","u32"],["value","u32"],["mode","u32"],["pad0","u32"]]),Dt=Ie.define("Fa2Params",[["n","u32"],["dim","u32"],["flags","u32"],["tierStart","u32"],["tierEnd","u32"],["iterationIndex","u32"],["seed","u32"],["nearMax","u32"],["scalingRatio","f32"],["gravity","f32"],["jitterTolerance","f32"],["scale","f32"],["center","vec4f"],["settleThreshold","f32"],["extentFactor","f32"],["gridMax","u32"],["levels","u32"],["arcBase","u32"],["arcEnd","u32"],["accumulate","u32"],["hiEnd","u32"],["frK","f32"],["temperature","f32"],["springLength","f32"],["springCoefficient","f32"],["coulomb","f32"],["dragCoefficient","f32"],["timeStep","f32"],["midEnd","u32"],["settleFloor","f32"]]),nn=Ie.define("Fa2State",[["speed","f32"],["speedEfficiency","f32"],["swing","f32"],["traction","f32"],["centroid","vec4f"],["rmsRadius","f32"],["radius","f32"],["meanDisplacement","f32"],["iteration","u32"],["min","vec4f"],["max","vec4f"],["gridMin","vec4f"],["eps","f32"],["settledCount","u32"],["outsideGrid","u32"],["maxCellOccupancy","u32"],["temperature","f32"],["kineticEnergy","f32"],["frEnergy","f32"],["frProgress","u32"],["invCellSize","f32"],["reserved0","f32"],["reserved1","vec2f"],["reserved2","vec4f"],["reserved3","vec4f"],["reserved4","vec4f"],["reserved5","vec4f"],["reserved6","vec4f"],["reserved7","vec4f"],["reserved8","vec4f"]],{layout:"storage",padTo:jt}),yo=Ie.define("Fa2Trace",[["swing","f32"],["traction","f32"],["speed","f32"],["speedEfficiency","f32"],["meanDisplacement","f32"],["settledCount","u32"],["iteration","u32"],["modelScalar","f32"]],{layout:"storage"}),hs=Ie.define("Fa2Partial",[["sum","vec4f"],["min","vec4f"],["max","vec4f"],["swingTraction","vec2f"],["dispFree","vec2f"]],{layout:"storage"}),pp=Ie.define("SpmvParams",[["n","u32"],["arcBase","u32"],["arcEnd","u32"],["stride","u32"],["alpha","f32"],["beta","f32"],["uniformP","f32"],["start","u32"]]),Ti=Ie.define("PrParams",[["n","u32"],["groups","u32"],["iteration","u32"],["trackConvergence","u32"],["convergeThreshold","f32"],["pad0","u32"],["pad1","u32"],["pad2","u32"]]),et=Ie.define("PrPartial",[["danglingMass","f32"],["delta","f32"],["firstConverged","u32"],["iteration","u32"],["norm","f32"],["pad0","f32"],["pad1","f32"],["pad2","f32"]],{layout:"storage"}),bo=Ie.define("WccParams",[["n","u32"],["items","u32"],["stride","u32"],["r","u32"],["flagIndex","u32"],["giant","u32"],["maxSteps","u32"],["pad0","u32"]]),Sx=Ie.define("IndirectParams",[["countIndex","u32"],["wg","u32"],["slot","u32"],["pad0","u32"]]),Oi=Ie.define("ScanParams",[["count","u32"],["pad0","u32"],["pad1","u32"],["pad2","u32"]]),mp=Ie.define("GridLevelParams",[["childBase","u32"],["parentBase","u32"],["parentSide","u32"],["parentCells","u32"],["depth","u32"],["pad0","u32"],["pad1","u32"],["pad2","u32"]]),$i=Ie.define("HistParams",[["count","u32"],["bins","u32"],["pad0","u32"],["pad1","u32"]]),Al=Ie.define("RadixParams",[["count","u32"],["shift","u32"],["groups","u32"],["pad0","u32"]]),gs=Ie.define("CompactParams",[["count","u32"],["outIndex","u32"],["countIndex","u32"],["stride","u32"]]),It=Ie.define("FrontierCounters",[["frontierCount","u32"],["nextFrontierCount","u32"],["frontierDegreeSum","u32"],["prevFrontierCount","u32"],["prevDegreeSum","u32"],["unvisitedCount","u32"],["unvisitedDegreeSum","u32"],["unvisitedListLen","u32"],["edgeCount","u32"],["edgeCountUnclamped","u32"],["overflowLevels","u32"],["level","u32"],["visitedCount","u32"],["switches","u32"],["direction","u32"],["done","u32"],["arcsScanned","u32"],["fusedLevels","u32"],["twoPhaseLevels","u32"],["bottomUpLevels","u32"],["farCount","u32"],["nextFarCount","u32"],["thresholdBits","u32"],["deltaBits","u32"],["path","u32"],["nextDegreeSum","u32"],["stackTop","u32"],["sigmaOverflow","u32"]],{layout:"storage"}),je=Ie.define("FrontierParams",[["role","u32"],["wg","u32"],["alpha","u32"],["beta","u32"],["fusedMax","u32"],["edgeCapacity","u32"],["maxDepth","u32"],["n","u32"],["mode","u32"],["cutoffBits","u32"],["arcBase","u32"],["arcEnd","u32"],["predKind","u32"],["bitsBase","u32"],["source","u32"],["stride","u32"],["firstOfSubmit","u32"],["iteration","u32"],["pad3","u32"],["pad2","u32"]]),or=Ie.define("BcParams",[["n","u32"],["k","u32"],["start","u32"],["count","u32"],["stride","u32"],["role","u32"],["pad0","u32"],["pad1","u32"]]),vo=Ie.define("ClosenessParams",[["role","u32"],["n","u32"],["words","u32"],["base","u32"],["total","u32"],["level","u32"],["row","u32"],["ctrl","u32"],["count","u32"],["source","u32"],["sourcesAt","u32"],["pullAt","u32"],["perNode","u32"],["arcCount","u32"],["pullOk","u32"],["pad0","u32"]]),yp=Ie.define("BfParams",[["edgeCount","u32"],["stride","u32"],["maxRetries","u32"],["cutoffBits","u32"]]),ws=Ie.define("BfFlags",[["changed","u32"],["retryExhausted","u32"],["pad0","u32"],["pad1","u32"]],{layout:"storage"}),Ri=Ie.define("ApspParams",[["n","u32"],["round","u32"],["blocks","u32"],["infBits","u32"]]),vn=Ie.define("CooParams",[["count","u32"],["pad0","u32"],["pad1","u32"],["pad2","u32"]]),bp=Ie.define("GroupParams",[["rowsBase","u32"],["basesBase","u32"],["count","u32"],["pad0","u32"]]),vp=Ie.define("LpaParams",[["n","u32"],["direction","u32"],["counterIndex","u32"],["pad0","u32"]]),Di=Ie.define("MstParams",[["count","u32"],["counterIndex","u32"],["pad0","u32"],["pad1","u32"]]);function _(n,e,t,r,o){return{group:n,binding:e,name:t,kind:r,wgslType:o}}const rn=[_(0,0,"rowPtr","storage-ro","array<u32>"),_(0,1,"colIdx","storage-ro","array<u32>"),_(0,2,"weights","storage-ro","array<f32>"),_(0,3,"perm","storage-ro","array<u32>")],Px={id:"degree",body:BP,entryPoint:"degree",bindings:rn.concat(_(1,0,"out","storage","array<u32>"),_(2,0,"P","uniform","RangeParams")),overrideDecls:[],uniforms:[vl],needs:[],snippetSlots:[],phase:"P1"},xx={id:"reduce",body:fx,entryPoint:"reduce",bindings:[_(1,0,"src","storage-ro","array<u32>"),_(1,1,"out","storage","array<u32>"),_(2,0,"P","uniform","ReduceParams")],overrideDecls:[{name:"OP",type:"u32",default:0},{name:"DTYPE",type:"u32",default:0},{name:"FINAL",type:"bool",default:!1}],uniforms:[kx],needs:["subgroups"],snippetSlots:[],phase:"P1"},Cx={id:"fill",body:HP,entryPoint:"fill",bindings:[_(1,0,"dst","storage","array<u32>"),_(2,0,"P","uniform","FillParams")],overrideDecls:[],uniforms:[Ze],needs:[],snippetSlots:[],phase:"P1"},Nx={id:"segmented-reduce",body:px,entryPoint:"segmented_reduce",bindings:rn.concat(_(1,0,"out","storage","array<f32>"),_(2,0,"P","uniform","RangeParams")),overrideDecls:[{name:"OP",type:"u32",default:0},{name:"TIER",type:"u32",default:0}],uniforms:[vl],needs:["subgroups"],snippetSlots:["VALUE"],phase:"P2"},Tx={id:"fa2-stats-finalize",body:jP,entryPoint:"stats_finalize",bindings:[_(1,0,"partials","storage-ro","array<Fa2Partial>"),_(1,1,"S","storage","Fa2State"),_(1,2,"T","storage","array<Fa2Trace>"),_(1,3,"cellHist","storage-ro","array<u32>"),_(1,4,"hubCounters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"STATS_MODE",type:"u32",default:0}],uniforms:[Dt,nn,yo,hs],needs:["subgroups"],snippetSlots:[],phase:"P3"},Ox={id:"fa2-attraction",body:zP,entryPoint:"attraction",bindings:rn.concat(_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"force","storage","array<f32>"),_(2,0,"P","uniform","Fa2Params")),overrideDecls:[{name:"LINLOG",type:"bool",default:!1},{name:"DISTRIBUTED",type:"bool",default:!1},{name:"TIER",type:"u32",default:0},{name:"LAW",type:"u32",default:0}],uniforms:[Dt],needs:["subgroups"],snippetSlots:[],phase:"P3"},$x={id:"fa2-repulsion-exact",body:WP,entryPoint:"repulsion",bindings:[_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"S","storage","Fa2State"),_(1,2,"force","storage","array<f32>"),_(1,3,"oldForce","storage-ro","array<f32>"),_(1,4,"fixedMask","storage-ro","array<u32>"),_(1,5,"partials","storage","array<Fa2Partial>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"SWING_MODE",type:"u32",default:0},{name:"STRONG_GRAVITY",type:"bool",default:!1},{name:"GRAVITY_CENTER",type:"u32",default:0},{name:"LAW",type:"u32",default:0}],uniforms:[Dt,nn,hs],needs:["subgroups"],snippetSlots:[],phase:"P1"},Rx={id:"fa2-speed-finalize",body:VP,entryPoint:"speed_finalize",bindings:[_(1,0,"partials","storage-ro","array<Fa2Partial>"),_(1,1,"S","storage","Fa2State"),_(1,2,"T","storage","array<Fa2Trace>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"SWING_MODE",type:"u32",default:0}],uniforms:[Dt,nn,yo,hs],needs:["subgroups"],snippetSlots:[],phase:"P1"},Dx={id:"fa2-integrate",body:GP,entryPoint:"integrate",bindings:[_(1,0,"force","storage-ro","array<f32>"),_(1,1,"oldForce","storage","array<f32>"),_(1,2,"fixedMask","storage-ro","array<u32>"),_(1,3,"S","storage","Fa2State"),_(1,4,"pos","storage","array<vec4f>"),_(1,5,"partials","storage","array<Fa2Partial>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"SWING_MODE",type:"u32",default:0},{name:"APPLY",type:"u32",default:0}],uniforms:[Dt,nn,hs],needs:["subgroups"],snippetSlots:[],phase:"P3"},Lx={id:"fa2-to-scene",body:qP,entryPoint:"to_scene",bindings:[_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"scene","storage","array<f32>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[],uniforms:[Dt],needs:[],snippetSlots:[],phase:"P3"},Mx={id:"spmv-pull",body:mx,entryPoint:"spmv_pull",bindings:rn.concat(_(1,0,"xNorm","storage-ro","array<f32>"),_(1,1,"rankOut","storage","array<f32>"),_(1,2,"personalization","storage-ro","array<f32>"),_(1,3,"partials","storage-ro","array<PrPartial>"),_(2,0,"P","uniform","SpmvParams")),overrideDecls:[{name:"HAS_PERSONALIZATION",type:"bool",default:!1},{name:"USE_DANGLING",type:"bool",default:!1},{name:"TIER",type:"u32",default:0}],uniforms:[pp,et],needs:["subgroups"],snippetSlots:[],phase:"P7"},Ux={id:"pr-scale",body:lx,entryPoint:"pr_scale",bindings:[_(1,0,"rankIn","storage-ro","array<f32>"),_(1,1,"rankPrev","storage-ro","array<f32>"),_(1,2,"outWeightSum","storage-ro","array<f32>"),_(1,3,"xNorm","storage","array<f32>"),_(1,4,"partials","storage","array<PrPartial>"),_(2,0,"P","uniform","PrParams")],overrideDecls:[{name:"NORM_MODE",type:"u32",default:0}],uniforms:[Ti,et],needs:["subgroups"],snippetSlots:[],phase:"P7"},Fx={id:"pr-finalize",body:cx,entryPoint:"pr_finalize",bindings:[_(1,0,"partials","storage","array<PrPartial>"),_(2,0,"P","uniform","PrParams")],overrideDecls:[{name:"NORM_MODE",type:"u32",default:0}],uniforms:[Ti,et],needs:["subgroups"],snippetSlots:[],phase:"P7"},Bx={id:"wcc-link-sample",body:_x,entryPoint:"wcc_link_sample",bindings:rn.concat(_(1,0,"comp","storage","array<atomic<u32>>"),_(2,0,"P","uniform","WccParams")),overrideDecls:[],uniforms:[bo],needs:[],snippetSlots:[],phase:"P7"},zx={id:"wcc-link-edges",body:Ex,entryPoint:"wcc_link_edges",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"comp","storage","array<atomic<u32>>"),_(2,0,"P","uniform","WccParams")],overrideDecls:[],uniforms:[bo],needs:[],snippetSlots:[],phase:"P7"},Gx={id:"wcc-compress",body:Ax,entryPoint:"wcc_compress",bindings:[_(1,0,"comp","storage","array<atomic<u32>>"),_(2,0,"P","uniform","WccParams")],overrideDecls:[],uniforms:[bo],needs:[],snippetSlots:[],phase:"P7"},Wx={id:"wcc-sample",body:Ix,entryPoint:"wcc_sample",bindings:[_(1,0,"comp","storage","array<atomic<u32>>"),_(1,1,"hist","storage","array<u32>"),_(2,0,"P","uniform","WccParams")],overrideDecls:[],uniforms:[bo],needs:[],snippetSlots:[],phase:"P7"},Vx={id:"indirect-finalize",body:rx,entryPoint:"indirect_finalize",bindings:[_(1,0,"counters","storage-ro","array<u32>"),_(1,1,"args","storage","array<u32>"),_(2,0,"P","uniform","IndirectParams")],overrideDecls:[],uniforms:[Sx],needs:[],snippetSlots:[],phase:"P4"},jx={id:"scan-block",body:wx,entryPoint:"scan_block",bindings:[_(1,0,"src","storage-ro","array<u32>"),_(1,1,"out","storage","array<u32>"),_(1,2,"blockSums","storage","array<u32>"),_(2,0,"P","uniform","ScanParams")],overrideDecls:[],uniforms:[Oi],needs:[],snippetSlots:[],phase:"P4"},qx={id:"scan-add",body:gx,entryPoint:"scan_add",bindings:[_(1,0,"out","storage","array<u32>"),_(1,1,"blockOffsets","storage-ro","array<u32>"),_(2,0,"P","uniform","ScanParams")],overrideDecls:[],uniforms:[Oi],needs:[],snippetSlots:[],phase:"P4"},Hx={id:"histogram",body:nx,entryPoint:"histogram",bindings:[_(1,0,"keys","storage-ro","array<u32>"),_(1,1,"hist","storage","array<atomic<u32>>"),_(2,0,"P","uniform","HistParams")],overrideDecls:[],uniforms:[$i],needs:[],snippetSlots:[],phase:"P4"},Kx={id:"counting-scatter",body:MP,entryPoint:"counting_scatter",bindings:[_(1,0,"keys","storage-ro","array<u32>"),_(1,1,"start","storage-ro","array<u32>"),_(1,2,"cursor","storage","array<atomic<u32>>"),_(1,3,"outIndex","storage","array<u32>"),_(2,0,"P","uniform","HistParams")],overrideDecls:[],uniforms:[$i],needs:[],snippetSlots:[],phase:"P4"},Yx={id:"radix-hist",body:ux,entryPoint:"radix_hist",bindings:[_(1,0,"keys","storage-ro","array<u32>"),_(1,1,"hist","storage","array<u32>"),_(2,0,"P","uniform","RadixParams")],overrideDecls:[],uniforms:[Al],needs:[],snippetSlots:[],phase:"P4"},Xx={id:"radix-scatter",body:dx,entryPoint:"radix_scatter",bindings:[_(1,0,"keys","storage-ro","array<u32>"),_(1,1,"vals","storage-ro","array<u32>"),_(1,2,"offsets","storage-ro","array<u32>"),_(1,3,"keysOut","storage","array<u32>"),_(1,4,"valsOut","storage","array<u32>"),_(2,0,"P","uniform","RadixParams")],overrideDecls:[],uniforms:[Al],needs:[],snippetSlots:[],phase:"P4"},Qx={id:"grid-cell-key",body:YP,entryPoint:"grid_cell_key",bindings:[_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"S","storage-ro","Fa2State"),_(1,2,"cellKey","storage","array<u32>"),_(1,3,"cellVal","storage","array<u32>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[],uniforms:[Dt,nn],needs:[],snippetSlots:[],phase:"P4"},Jx={id:"grid-centroid",body:XP,entryPoint:"grid_centroid",bindings:[_(1,0,"sortedIdx","storage-ro","array<u32>"),_(1,1,"cellStart","storage-ro","array<u32>"),_(1,2,"pos","storage-ro","array<vec4f>"),_(1,3,"pyramid","storage","array<vec4f>"),_(1,4,"hubList","storage","array<u32>"),_(1,5,"hubCounters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[],uniforms:[Dt],needs:[],snippetSlots:[],phase:"P4"},Zx={id:"grid-centroid-hub",body:QP,entryPoint:"grid_centroid_hub",bindings:[_(1,0,"sortedIdx","storage-ro","array<u32>"),_(1,1,"cellStart","storage-ro","array<u32>"),_(1,2,"pos","storage-ro","array<vec4f>"),_(1,3,"pyramid","storage","array<vec4f>"),_(1,4,"hubList","storage-ro","array<u32>"),_(1,5,"hubCount","storage-ro","array<u32>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[],uniforms:[Dt],needs:["subgroups"],snippetSlots:[],phase:"P4"},eC={id:"grid-downsample",body:JP,entryPoint:"grid_downsample",bindings:[_(1,0,"pyramid","storage","array<vec4f>"),_(2,0,"P","uniform","GridLevelParams")],overrideDecls:[],uniforms:[mp],needs:[],snippetSlots:[],phase:"P4"},tC={id:"grid-far-field",body:ZP,entryPoint:"grid_far_field",bindings:[_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"sortedIdx","storage-ro","array<u32>"),_(1,2,"pyramid","storage-ro","array<vec4f>"),_(1,3,"S","storage-ro","Fa2State"),_(1,4,"force","storage","array<f32>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"LAW",type:"u32",default:0}],uniforms:[Dt,nn],needs:[],snippetSlots:[],phase:"P4"},nC={id:"grid-near-field",body:ex,entryPoint:"grid_near_field",bindings:[_(1,0,"pos","storage-ro","array<vec4f>"),_(1,1,"sortedIdx","storage-ro","array<u32>"),_(1,2,"cellStart","storage-ro","array<u32>"),_(1,3,"S","storage","Fa2State"),_(1,4,"force","storage","array<f32>"),_(1,5,"oldForce","storage-ro","array<f32>"),_(1,6,"fixedMask","storage-ro","array<u32>"),_(1,7,"partials","storage","array<Fa2Partial>"),_(2,0,"P","uniform","Fa2Params")],overrideDecls:[{name:"SWING_MODE",type:"u32",default:0},{name:"STRONG_GRAVITY",type:"bool",default:!1},{name:"GRAVITY_CENTER",type:"u32",default:0},{name:"LAW",type:"u32",default:0}],uniforms:[Dt,nn,hs],needs:["subgroups"],snippetSlots:[],phase:"P4"},rC={id:"compact-scatter",body:RP,entryPoint:"compact_scatter",bindings:[_(1,0,"queue","storage-ro","array<u32>"),_(1,1,"flags","storage-ro","array<u32>"),_(1,2,"offsets","storage-ro","array<u32>"),_(1,3,"out","storage","array<u32>"),_(1,4,"outCount","storage","array<u32>"),_(2,0,"P","uniform","CompactParams")],overrideDecls:[],uniforms:[gs],needs:[],snippetSlots:[],phase:"P8"},oC={id:"dedupe-claim",body:UP,entryPoint:"dedupe_claim",bindings:[_(1,0,"queue","storage-ro","array<u32>"),_(1,1,"owner","storage","array<atomic<u32>>"),_(1,2,"counters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","CompactParams")],overrideDecls:[],uniforms:[gs],needs:[],snippetSlots:[],phase:"P8"},sC={id:"dedupe-filter",body:FP,entryPoint:"dedupe_filter",bindings:[_(1,0,"queue","storage-ro","array<u32>"),_(1,1,"owner","storage","array<atomic<u32>>"),_(1,2,"out","storage","array<u32>"),_(1,3,"outCount","storage","array<atomic<u32>>"),_(2,0,"P","uniform","CompactParams")],overrideDecls:[],uniforms:[gs],needs:[],snippetSlots:[],phase:"P8"},iC={id:"frontier-finalize",body:KP,entryPoint:"frontier_finalize",bindings:[_(1,0,"counters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","FrontierParams")],overrideDecls:[],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},aC={id:"advance-expand",body:wP,entryPoint:"advance_expand",bindings:rn.concat(_(1,0,"frontierIn","storage-ro","array<u32>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"edgeQueue","storage","array<u32>"),_(2,0,"P","uniform","FrontierParams")),overrideDecls:[],uniforms:[je],needs:["subgroups"],snippetSlots:[],phase:"P8"},cC={id:"bfs-contract",body:xP,entryPoint:"bfs_contract",bindings:[_(1,0,"edgeQueue","storage-ro","array<u32>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"depth","storage","array<atomic<u32>>"),_(1,3,"frontierOut","storage","array<u32>"),_(2,0,"P","uniform","FrontierParams")],overrideDecls:[],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},lC={id:"sssp-pred",body:yx,entryPoint:"sssp_pred",bindings:rn.concat(_(1,0,"dist","storage-ro","array<u32>"),_(1,1,"pred","storage","array<atomic<u32>>"),_(2,0,"P","uniform","FrontierParams")),overrideDecls:[{name:"MODE",type:"u32",default:0}],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},uC={id:"bfs-fused",body:CP,entryPoint:"bfs_fused",bindings:rn.concat(_(1,0,"frontierIn","storage-ro","array<u32>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"depth","storage","array<atomic<u32>>"),_(1,3,"frontierOut","storage","array<u32>"),_(2,0,"P","uniform","FrontierParams")),overrideDecls:[],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},dC={id:"bfs-bottom-up",body:PP,entryPoint:"bfs_bottom_up",bindings:rn.concat(_(1,0,"sweepIn","storage-ro","array<u32>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"depth","storage","array<atomic<u32>>"),_(1,3,"frontierOut","storage","array<u32>"),_(2,0,"P","uniform","FrontierParams")),overrideDecls:[],uniforms:[je],needs:["subgroups"],snippetSlots:[],phase:"P8"},fC={id:"bfs-bitset-build",body:SP,entryPoint:"bfs_bitset_build",bindings:[_(1,0,"frontierIn","storage-ro","array<u32>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"bits","storage","array<atomic<u32>>"),_(2,0,"P","uniform","FrontierParams")],overrideDecls:[],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},hC={id:"bfs-unvisited-flags",body:TP,entryPoint:"bfs_unvisited_flags",bindings:[_(1,0,"inDegree","storage-ro","array<u32>"),_(1,1,"depth","storage-ro","array<u32>"),_(1,2,"flags","storage","array<u32>"),_(1,3,"counters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","FrontierParams")],overrideDecls:[],uniforms:[je],needs:["subgroups"],snippetSlots:[],phase:"P8"},gC={id:"bfs-next-degree",body:NP,entryPoint:"bfs_next_degree",bindings:[_(1,0,"frontier","storage-ro","array<u32>"),_(1,1,"outDegree","storage-ro","array<u32>"),_(1,2,"counters","storage","array<atomic<u32>>"),_(1,3,"inDegree","storage-ro","array<u32>"),_(2,0,"P","uniform","FrontierParams")],overrideDecls:[],uniforms:[je],needs:["subgroups"],snippetSlots:[],phase:"P8"},wC={id:"sssp-relax",body:bx,entryPoint:"sssp_relax",bindings:rn.concat(_(1,0,"dist","storage","array<atomic<u32>>"),_(1,1,"counters","storage","array<atomic<u32>>"),_(1,2,"queueIn","storage-ro","array<u32>"),_(1,3,"queueOut","storage","array<u32>"),_(2,0,"P","uniform","FrontierParams")),overrideDecls:[],uniforms:[je],needs:[],snippetSlots:[],phase:"P8"},pC={id:"bf-relax",body:kP,entryPoint:"bf_relax",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"edgeToArc","storage-ro","array<u32>"),_(1,3,"weights","storage-ro","array<f32>"),_(1,4,"dist","storage","array<atomic<u32>>"),_(1,5,"flags","storage","array<atomic<u32>>"),_(2,0,"P","uniform","BfParams")],overrideDecls:[{name:"UNDIRECTED",type:"bool",default:!1}],uniforms:[yp],needs:[],snippetSlots:[],phase:"P8"},mC={id:"closeness-level",body:OP,entryPoint:"closeness_level",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"inRowPtr","storage-ro","array<u32>"),_(1,3,"inColIdx","storage-ro","array<u32>"),_(1,4,"bits","storage","array<atomic<u32>>"),_(1,5,"table","storage","array<atomic<u32>>"),_(2,0,"P","uniform","ClosenessParams")],overrideDecls:[],uniforms:[vo],needs:[],snippetSlots:[],phase:"P8"},yC={id:"closeness-rowsum",body:$P,entryPoint:"closeness_rowsum",bindings:[_(1,0,"dist","storage-ro","array<f32>"),_(1,1,"out","storage","array<u32>"),_(2,0,"P","uniform","ClosenessParams")],overrideDecls:[],uniforms:[vo],needs:[],snippetSlots:[],phase:"P9"},bC={id:"bc-finalize",body:AP,entryPoint:"bc_finalize",bindings:[_(1,0,"counters","storage","array<atomic<u32>>"),_(1,1,"ends","storage","array<u32>"),_(1,2,"S","storage-ro","array<u32>"),_(1,3,"depthK","storage","array<u32>"),_(1,4,"sigmaK","storage","array<u32>"),_(1,5,"levelMax","storage","array<u32>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[{name:"SCALED",type:"bool",default:!1}],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},vC={id:"bc-forward",body:EP,entryPoint:"bc_forward",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"S","storage","array<u32>"),_(1,3,"ends","storage-ro","array<u32>"),_(1,4,"counters","storage","array<atomic<u32>>"),_(1,5,"depthK","storage","array<atomic<u32>>"),_(1,6,"sigmaK","storage","array<atomic<u32>>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[{name:"SCALED",type:"bool",default:!1}],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},AC={id:"bc-backward",body:yP,entryPoint:"bc_backward",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"S","storage-ro","array<u32>"),_(1,3,"depthK","storage-ro","array<u32>"),_(1,4,"sigmaK","storage-ro","array<u32>"),_(1,5,"deltaK","storage","array<f32>"),_(1,6,"levelMax","storage-ro","array<u32>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[{name:"SCALED",type:"bool",default:!1}],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},EC={id:"bc-gather",body:IP,entryPoint:"bc_gather",bindings:[_(1,0,"deltaK","storage-ro","array<f32>"),_(1,1,"bc","storage","array<f32>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},_C={id:"bc-edge-gather",body:vP,entryPoint:"bc_edge_gather",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"depthK","storage-ro","array<u32>"),_(1,3,"sigmaK","storage-ro","array<u32>"),_(1,4,"deltaK","storage-ro","array<f32>"),_(1,5,"arcScores","storage","array<f32>"),_(1,6,"levelMax","storage-ro","array<u32>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[{name:"SCALED",type:"bool",default:!1}],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},IC={id:"bc-forward-edge",body:_P,entryPoint:"bc_forward_edge",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"S","storage","array<u32>"),_(1,3,"ends","storage-ro","array<u32>"),_(1,4,"counters","storage","array<atomic<u32>>"),_(1,5,"depthK","storage","array<atomic<u32>>"),_(1,6,"sigmaK","storage","array<atomic<u32>>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[{name:"UNDIRECTED",type:"bool",default:!1},{name:"SCALED",type:"bool",default:!1}],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},kC={id:"bc-count",body:bP,entryPoint:"bc_count",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"S","storage-ro","array<u32>"),_(1,3,"ends","storage-ro","array<u32>"),_(1,4,"counters","storage","array<atomic<u32>>"),_(1,5,"depthK","storage-ro","array<u32>"),_(1,6,"sigmaK","storage","array<u32>"),_(1,7,"levelMax","storage","array<atomic<u32>>"),_(2,0,"P","uniform","BcParams")],overrideDecls:[],uniforms:[or],needs:[],snippetSlots:[],phase:"P9"},SC={id:"apsp-init",body:mP,entryPoint:"apsp_init",bindings:rn.concat(_(1,0,"dist","storage","array<f32>"),_(2,0,"P","uniform","ApspParams")),overrideDecls:[],uniforms:[Ri],needs:[],snippetSlots:[],phase:"P9"},PC={id:"apsp-fw",body:pP,entryPoint:"apsp_fw",bindings:[_(1,0,"dist","storage","array<f32>"),_(2,0,"P","uniform","ApspParams")],overrideDecls:[{name:"PHASE",type:"u32",default:0}],uniforms:[Ri],needs:[],snippetSlots:[],phase:"P9"},xC={id:"coo-emit",body:DP,entryPoint:"coo_emit",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"edgeWeight","storage-ro","array<f32>"),_(1,3,"order","storage-ro","array<u32>"),_(1,4,"outSrc","storage","array<u32>"),_(1,5,"outDst","storage","array<u32>"),_(1,6,"outWeight","storage","array<f32>"),_(2,0,"P","uniform","CooParams")],overrideDecls:[{name:"INDEXED",type:"bool",default:!1},{name:"WEIGHTED",type:"bool",default:!1}],uniforms:[vn],needs:[],snippetSlots:[],phase:"P11"},CC={id:"run-flags",body:hx,entryPoint:"run_flags",bindings:[_(1,0,"keysA","storage-ro","array<u32>"),_(1,1,"keysB","storage-ro","array<u32>"),_(1,2,"flags","storage","array<u32>"),_(2,0,"P","uniform","CooParams")],overrideDecls:[],uniforms:[vn],needs:[],snippetSlots:[],phase:"P11"},NC={id:"coo-scatter",body:LP,entryPoint:"coo_scatter",bindings:[_(1,0,"src","storage-ro","array<u32>"),_(1,1,"dst","storage-ro","array<u32>"),_(1,2,"weight","storage-ro","array<f32>"),_(1,3,"rowPtr","storage-ro","array<u32>"),_(1,4,"cursors","storage","array<atomic<u32>>"),_(1,5,"colIdx","storage","array<u32>"),_(1,6,"outWeight","storage","array<f32>"),_(2,0,"P","uniform","CooParams")],overrideDecls:[{name:"SORTED_INPUT",type:"bool",default:!1},{name:"WEIGHTED",type:"bool",default:!1}],uniforms:[vn],needs:[],snippetSlots:[],phase:"P11"},TC={id:"orient-flags",body:ax,entryPoint:"orient_flags",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"src","storage-ro","array<u32>"),_(1,3,"flags","storage","array<u32>"),_(2,0,"P","uniform","CooParams")],overrideDecls:[],uniforms:[vn],needs:[],snippetSlots:[],phase:"P11"},OC={id:"tri-intersect",body:vx,entryPoint:"tri_intersect",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"src","storage-ro","array<u32>"),_(1,3,"counts","storage","array<atomic<u32>>"),_(2,0,"P","uniform","CooParams")],overrideDecls:[{name:"SEARCH",type:"u32",default:0}],uniforms:[vn],needs:[],snippetSlots:[],phase:"P11"},$C={id:"group-by-key-row",body:tx,entryPoint:"group_by_key_row",bindings:[_(1,0,"rowPtr","storage-ro","array<u32>"),_(1,1,"colIdx","storage-ro","array<u32>"),_(1,2,"weights","storage-ro","array<f32>"),_(1,3,"keyIn","storage-ro","array<u32>"),_(1,4,"rows","storage-ro","array<u32>"),_(1,5,"hashRegion","storage","array<atomic<u32>>"),_(1,6,"bestKey","storage","array<u32>"),_(1,7,"bestScore","storage","array<f32>"),_(2,0,"P","uniform","GroupParams")],overrideDecls:[{name:"TIER",type:"u32",default:0},{name:"WEIGHTED",type:"bool",default:!1}],uniforms:[bp],needs:[],snippetSlots:[],phase:"P11"},RC={id:"lpa-step",body:ox,entryPoint:"lpa_step",bindings:[_(1,0,"labelsIn","storage-ro","array<u32>"),_(1,1,"bestKey","storage-ro","array<u32>"),_(1,2,"labelsOut","storage","array<u32>"),_(1,3,"counters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","LpaParams")],overrideDecls:[],uniforms:[vp],needs:[],snippetSlots:[],phase:"P11"},DC={id:"mst-best",body:sx,entryPoint:"mst_best",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"edgeWeight","storage-ro","array<f32>"),_(1,3,"comp","storage-ro","array<u32>"),_(1,4,"bestKey","storage","array<atomic<u32>>"),_(1,5,"bestEdge","storage","array<atomic<u32>>"),_(2,0,"P","uniform","MstParams")],overrideDecls:[{name:"PASS",type:"u32",default:0},{name:"WEIGHTED",type:"bool",default:!1}],uniforms:[Di],needs:[],snippetSlots:[],phase:"P11"},LC={id:"mst-link",body:ix,entryPoint:"mst_link",bindings:[_(1,0,"edgeSrc","storage-ro","array<u32>"),_(1,1,"edgeDst","storage-ro","array<u32>"),_(1,2,"bestEdge","storage-ro","array<u32>"),_(1,3,"comp","storage","array<atomic<u32>>"),_(1,4,"treeEdge","storage","array<u32>"),_(1,5,"counters","storage","array<atomic<u32>>"),_(2,0,"P","uniform","MstParams")],overrideDecls:[],uniforms:[Di],needs:[],snippetSlots:[],phase:"P11"},Ap=Object.freeze({degree:Px,reduce:xx,fill:Cx,"segmented-reduce":Nx,"fa2-stats-finalize":Tx,"fa2-attraction":Ox,"fa2-repulsion-exact":$x,"fa2-speed-finalize":Rx,"fa2-integrate":Dx,"fa2-to-scene":Lx,"spmv-pull":Mx,"pr-scale":Ux,"pr-finalize":Fx,"wcc-link-sample":Bx,"wcc-link-edges":zx,"wcc-compress":Gx,"wcc-sample":Wx,"indirect-finalize":Vx,"scan-block":jx,"scan-add":qx,histogram:Hx,"counting-scatter":Kx,"radix-hist":Yx,"radix-scatter":Xx,"grid-cell-key":Qx,"grid-centroid":Jx,"grid-centroid-hub":Zx,"grid-downsample":eC,"grid-far-field":tC,"grid-near-field":nC,"compact-scatter":rC,"dedupe-claim":oC,"dedupe-filter":sC,"frontier-finalize":iC,"advance-expand":aC,"bfs-contract":cC,"sssp-pred":lC,"bfs-fused":uC,"bfs-bottom-up":dC,"bfs-bitset-build":fC,"bfs-unvisited-flags":hC,"bfs-next-degree":gC,"sssp-relax":wC,"bf-relax":pC,"closeness-level":mC,"closeness-rowsum":yC,"bc-finalize":bC,"bc-forward":vC,"bc-backward":AC,"bc-gather":EC,"bc-count":kC,"bc-edge-gather":_C,"bc-forward-edge":IC,"apsp-init":SC,"apsp-fw":PC,"coo-emit":xC,"run-flags":CC,"coo-scatter":NC,"orient-flags":TC,"tri-intersect":OC,"group-by-key-row":$C,"lpa-step":RC,"mst-best":DC,"mst-link":LC}),MC=new Map;function UC(n){const e=Ap[n];if(e===void 0)throw new S("E_INVALID_ARGUMENT",`unknown kernel id "${n}"`,{argument:"id",value:n,expected:Object.keys(Ap)});return e}function z(n,e,t){const r=UC(n);return{id:r.id,body:MC.get(n)??r.body,bindings:r.bindings,overrideDecls:r.overrideDecls,overrides:e??{},needs:r.needs,uniforms:r.uniforms,snippets:t}}function on(n,e,t){const r=n.colIdx??n.rowPtr,o=t===void 0?n.weights:t;return{rowPtr:n.rowPtr,colIdx:r,weights:o??r,perm:e??n.rowPtr}}function Ct(n,e,t){const r=t===void 0?n.weights:t;return{USE_PERM:e!==null,HAS_WEIGHTS:r!==null}}const Mn=32;function FC(n){const{perm:e}=n.bindings;if(e===void 0)throw new S("E_INVALID_ARGUMENT",`the ${n.view} view has no perm binding`,{argument:"view",value:n.view,expected:"a view with a perm binding (degreeOrder, reverseDegreeOrder)"});const t=n.scalars.segmentOffsets;if(!(t?.length===5&&t[0]===0&&t.every((s,i)=>Number.isInteger(s)&&(i===0||s>=t[i-1])))||t[4]!==e.size/4)throw new S("E_INVALID_ARGUMENT",`the ${n.view} view's segmentOffsets are not five ascending numbers ending at the row count`,{argument:"view",value:t===void 0?null:Array.from(t),expected:`[0, hiEnd, midEnd, lowEnd, ${e.size/4}] ascending`});const o=[t[0],t[1],t[2],t[3],t[4]];return Object.freeze({perm:e,segmentOffsets:o})}function ps(n,e){const t=n.rowPtr.size;if(t<4||t%4!==0)throw new S("E_INVALID_ARGUMENT",`${e}: a rowPtr binding of ${t} bytes is not 4(n + 1)`,{argument:"core.rowPtr",value:t,expected:"a positive multiple of 4"});return t/4-1}function Li(n){return n.colIdx===null?0:n.colIdx.size/4}function Mi(n,e,t){const r=n.arcBuffers?.[e][t.bufferIndex];if(r===void 0)throw new S("E_INVALID_ARGUMENT",`windowBinding: the core has no window buffers of ${e}`,{argument:"core",value:e,expected:"a windowed core whose plan uploaded the array"});return{buffer:r,offset:t.offset,size:4*(t.end-t.start),window:t}}function El(n){return n.windows===null?[{arcBase:0,arcEnd:Li(n),core:n}]:n.windows.map((e,t,r)=>({arcBase:e.start,arcEnd:t+1<r.length?r[t+1].start:e.end,core:{...n,colIdx:Mi(n,"colIdx",e),weights:n.weights===null?null:Mi(n,"weights",e)}}))}function BC(n,e){if(n.plan==="windowed"||n.windows!==null)throw new S("E_UNSUPPORTED",`${e}: windowed cores are not executed by the pull`,{feature:`${e}.windowed`})}function sr(n,e,t,r){if(n.plan==="windowed")throw new S("E_TOO_LARGE",`${r}: the arc arrays need a windowed upload (${n.windows?.length??0} windows), which ${r} does not execute (DEP-P4-B)`,{needed:4*e,limit:t,path:"windowed",algorithm:r})}function Ui(n,e){const{rowPtr:t}=n.bindings;if(t===void 0)throw new S("E_INVALID_ARGUMENT",`the ${n.view} view has no rowPtr binding`,{argument:"view",value:n.view,expected:"a view with a rowPtr binding (reverse)"});const r=n.bindings.colIdx===void 0||n.bindings.colIdx.size===0?null:n.bindings.colIdx,o=n.bindings.weights===void 0||n.bindings.weights.size===0?null:n.bindings.weights,s=r===null?0:r.size/4;if(s!==e)throw new S("E_INVALID_ARGUMENT",`the ${n.view} view binds ${s} arcs but its arcCount scalar says ${e}`,{argument:"arcCount",value:e,expected:s});return Object.freeze({serial:-1,plan:"perArray",rowPtr:t,colIdx:r,weights:o,arcToEdge:null,edgeToArc:null,windows:null,arcBuffers:null,hasWeights:o!==null})}class _l{constructor(e,t,r,o){if(this.overruns=0,this.next=0,this.dirtyLo=-1,this.dirtyHi=-1,this.destroyed=!1,!Number.isInteger(r)||r<1)throw new S("E_INVALID_ARGUMENT",`UniformRing "${o}": slots must be a positive integer, got ${r}`,{argument:"slots",value:r,expected:"an integer >= 1"});this.device=e,this.allocator=t,this.slots=r,this.label=o,this.shadow=new ArrayBuffer(r*Vt),this.view=new DataView(this.shadow),this.dirty=new Uint8Array(r),this.buffer=t.createBuffer({label:o,size:r*Vt,usage:Se.UNIFORM|Se.COPY_DST})}binding(e){return this.assertLive(),this.assertFits(e),{buffer:this.buffer,offset:0,size:e.byteLength,window:null}}offsetOf(e){return this.checkSlot(e),e*Vt}reserve(e){if(this.assertLive(),!Number.isInteger(e)||e<1||e>this.slots)throw new S("E_INVALID_ARGUMENT",`UniformRing "${this.label}": cannot reserve ${e} of ${this.slots} slots`,{argument:"count",value:e,expected:`an integer in [1, ${this.slots}]`});this.next+e>this.slots&&(this.next=0);const t=this.next;return this.next+=e,this.dirty.subarray(t,t+e).includes(1)&&(this.overruns+=1),t}write(e,t,r){this.checkSlot(e),this.assertFits(t),t.write(this.view,r,e*Vt),this.dirty[e]=1,(this.dirtyLo<0||e<this.dirtyLo)&&(this.dirtyLo=e),e>this.dirtyHi&&(this.dirtyHi=e)}flush(){if(this.assertLive(),this.dirtyLo<0)return;const e=this.dirtyLo*Vt,t=(this.dirtyHi+1)*Vt;this.device.queue.writeBuffer(this.buffer,e,this.shadow,e,t-e),this.dirty.fill(0),this.dirtyLo=-1,this.dirtyHi=-1}destroy(){this.destroyed||(this.destroyed=!0,this.allocator.destroy(this.buffer))}assertLive(){if(this.destroyed)throw new S("E_DISPOSED",`UniformRing "${this.label}" is destroyed`,{label:this.label})}checkSlot(e){if(this.assertLive(),!Number.isInteger(e)||e<0||e>=this.slots)throw new S("E_INVALID_ARGUMENT",`UniformRing "${this.label}": slot ${e} is outside [0, ${this.slots})`,{argument:"slot",value:e,expected:`an integer in [0, ${this.slots})`})}assertFits(e){if(e.byteLength>Vt)throw new S("E_INVALID_ARGUMENT",`UniformRing "${this.label}": block ${e.name} is ${e.byteLength} bytes, a slot holds ${Vt}`,{argument:"block",value:e.name,expected:`byteLength <= ${Vt}`})}}const zC=4294967295;async function Or(n){const e=await n.pipelines.kernel(z("scan-block")),t=await n.pipelines.kernel(z("scan-add")),r=n.scratch(4,"scan/zero");return n.device.queue.writeBuffer(r,0,new Uint32Array(1)),new WC(n,e,t,{buffer:r,offset:0,size:4,window:null})}function GC(n,e,t){if(!Number.isSafeInteger(e)||e<0||e>zC)throw new S("E_INVALID_ARGUMENT","scan: count must be a non-negative integer below 2^32",{argument:"count",value:e});if(n.size<4*e)throw new S("E_INVALID_ARGUMENT","scan: src is smaller than 4 x count bytes",{argument:"src",value:n.size,expected:4*e});if(t.size<4*e)throw new S("E_INVALID_ARGUMENT","scan: out is smaller than 4 x count bytes",{argument:"out",value:t.size,expected:4*e})}class WC{constructor(e,t,r,o){this.dispatches=0,this.scope=e,this.block=t,this.add=r,this.zero=o}get lastDispatches(){return this.dispatches}record(e,t,r,o){if(GC(t,r,o),r===0)return this.dispatches=0,{binding:this.zero,index:0};const s=this.scope.workgroupSize,i=[];let a=t,c=o,l=r;for(;;){const d=Math.ceil(l/s),f=se(l,s,this.scope.caps),h=yl(f),g=this.scratch(h,`scan/sums${i.length}`);if(i.push({input:a,output:c,count:l,plan:f,sums:g}),d===1)break;a=g,c=this.scratch(h,`scan/offsets${i.length}`),l=d}for(const d of i){const f=this.scope.params(Oi,{count:d.count,pad0:0,pad1:0,pad2:0}),h=this.block.bind({src:d.input,out:d.output,blockSums:d.sums,P:f.binding});this.block.dispatch(e,h,d.plan,[f.offset])}for(let d=i.length-2;d>=0;d--){const f=i[d],h=this.scope.params(Oi,{count:f.count,pad0:0,pad1:0,pad2:0}),g=this.add.bind({out:f.output,blockOffsets:i[d+1].output,P:h.binding});this.add.dispatch(e,g,f.plan,[h.offset])}return this.dispatches=2*i.length-1,{binding:i[i.length-1].sums,index:0}}scratch(e,t){const r=4*e;return{buffer:this.scope.scratch(r,t),offset:0,size:r,window:null}}}const Fi=3735928559,Ep=32,VC=8,Il=new WeakMap;function _p(n){return n+1}function jC(n,e,t){let r=0;for(let o=0;o<t;o++){const s=n[o];if(s!==r)return{where:`out[${String(o)}]`,expected:r,actual:s,poison:s===Fi};r=r+_p(o)>>>0}return e!==r?{where:"total",expected:r,actual:e,poison:e===Fi}:null}function Ip(n,e){return{buffer:n,offset:0,size:e,window:null}}async function qC(n){const e=performance.now(),t=n.workgroupSize,r=Ep*t+1,o=4*r,s=n.pool.lease(),i=new _l(n.device,n.allocator,VC,"device-check/ring");try{const a={device:n.device,caps:n.caps,pipelines:n.pipelines,pool:n.pool,workgroupSize:t,scratch:(y,b)=>s.storage(y,`device-check/${b}`),params(y,b){const v=i.reserve(1);return i.write(v,y,b),{binding:i.binding(y),offset:i.offsetOf(v)}}},c=await Or(a),l=s.storage(o,"device-check/src"),u=s.storage(o,"device-check/out"),d=new Uint32Array(r);for(let y=0;y<r;y++)d[y]=_p(y);n.device.queue.writeBuffer(l,0,d),n.device.queue.writeBuffer(u,0,new Uint32Array(r).fill(Fi));const f=n.device.createCommandEncoder({label:"device-check"}),h=f.beginComputePass({label:"device-check"}),g=c.record(h,Ip(l,o),r,Ip(u,o));h.end(),i.flush(),n.device.queue.submit([f.finish()]);const w=new Uint32Array(await n.readback.read(u,o)),p=new Uint32Array(await n.readback.read(g.binding.buffer,4,void 0,g.binding.offset+4*g.index)),m=jC(w,p[0],r);return{check:"exclusive-scan",ok:m===null,workgroupSize:t,count:r,blocks:Ep,ms:performance.now()-e,vendor:n.caps.vendor,architecture:n.caps.architecture,description:n.caps.description,mismatch:m}}finally{i.destroy(),s.release()}}function kp(n){const e=Il.get(n.device);if(e!==void 0)return e;const t=qC(n).catch(r=>{throw Il.delete(n.device),r});return Il.set(n.device,t),t}async function Lt(n){const e=await kp(n),{mismatch:t}=e;if(t===null)return;const r={vendor:e.vendor,architecture:e.architecture,device:n.caps.device,description:e.description},o=e.architecture==="warp"?"this is the Microsoft Basic Render Driver; the Microsoft.Direct3D.WARP redistributable (1.0.21 or newer) beside the host executable computes it correctly":void 0,s=t.poison?`${t.where} was never written (the ${String(Fi)} the check wrote beforehand survived the dispatch)`:`${t.where} came back as ${String(t.actual)} where ${String(t.expected)} was required`,i=`this device computes multi-workgroup shaders incorrectly: an exclusive scan of ${String(e.count)} known numbers is wrong -- ${s}. Refusing to run: every number this package computed here would be unreliable. adapter: ${r.vendor}/${r.architecture} "${r.description}"`;throw new S("E_DEVICE_INCORRECT",o===void 0?i:`${i}. ${o}`,{check:e.check,where:t.where,expected:t.expected,actual:t.actual,poison:t.poison,count:e.count,blocks:e.blocks,workgroupSize:e.workgroupSize,adapter:r,...o===void 0?{}:{hint:o}})}function Mt(n,e,t){const r=n.pool.lease(),o=new _l(n.device,n.allocator,t,`${e}/ring`);return{device:n.device,caps:n.caps,pipelines:n.pipelines,pool:n.pool,workgroupSize:n.workgroupSize,scratch:(s,i)=>r.storage(s,`${e}/${i}`),params(s,i){const a=o.reserve(1);return o.write(a,s,i),{binding:o.binding(s),offset:o.offsetOf(a)}},flush:()=>{o.flush()},dispose(){o.destroy(),r.release()},ringOverruns:()=>o.overruns}}async function Bi(n){const e=await n.pipelines.kernel(z("compact-scatter")),t=await n.pipelines.kernel(z("dedupe-claim")),r=await n.pipelines.kernel(z("dedupe-filter")),o=await Or(n);return new YC(n,e,t,r,o)}function Sp(n,e){if(!Number.isSafeInteger(e)||e<0||e>Ve)throw new S("E_INVALID_ARGUMENT",`${n}: count must be a non-negative integer below 2^32`,{argument:"count",value:e})}function ms(n,e,t,r){if(t.size<4*r)throw new S("E_INVALID_ARGUMENT",`${n}: ${e} is smaller than 4 x ${r} bytes`,{argument:e,value:t.size,expected:4*r})}function kl(n,e,t,r){if(!Number.isSafeInteger(t)||t<0||4*(t+1)>r.size)throw new S("E_INVALID_ARGUMENT",`${n}: ${e} ${t} is outside the block`,{argument:e,value:t,expected:`0 <= ${e} < ${Math.floor(r.size/4)}`})}function HC(n){Sp("compact",n.count),ms("compact","queue",n.queue,n.count),ms("compact","flags",n.flags,n.count),ms("compact","out",n.out,n.count),kl("compact","outIndex",n.outIndex,n.outCount)}function KC(n){if(Sp("dedupe",n.count),ms("dedupe","queue",n.queue,n.count),ms("dedupe","out",n.out,Math.min(n.count,Math.floor(n.owner.size/4))),kl("dedupe","outIndex",n.outIndex,n.outCount),n.countIndex!==Ve){if(kl("dedupe","countIndex",n.countIndex,n.counters),n.countIndex===n.outIndex)throw new S("E_INVALID_ARGUMENT","dedupe: countIndex must not be the output word outIndex",{argument:"countIndex",value:n.countIndex});if(n.counters.buffer!==n.outCount.buffer||n.counters.offset!==n.outCount.offset||n.counters.size!==n.outCount.size)throw new S("E_INVALID_ARGUMENT","dedupe: counters must be the same range as outCount when countIndex names a device word",{argument:"counters",value:n.counters.size,expected:n.outCount.size})}}class YC{constructor(e,t,r,o,s){this.dispatches=0,this.scope=e,this.scatter=t,this.claim=r,this.filter=o,this.scan=s}get lastDispatches(){return this.dispatches}record(e,t){if(HC(t),t.count===0){this.dispatches=0;return}const r=4*t.count,o={buffer:this.scope.scratch(r,"compact/offsets"),offset:0,size:r,window:null};this.scan.record(e,t.flags,t.count,o);const s=this.scope.params(gs,{count:t.count,outIndex:t.outIndex,countIndex:Ve,stride:0}),i=this.scatter.bind({queue:t.queue,flags:t.flags,offsets:o,out:t.out,outCount:t.outCount,P:s.binding});this.scatter.dispatch(e,i,se(t.count,this.scope.workgroupSize,this.scope.caps),[s.offset]),this.dispatches=this.scan.lastDispatches+1}recordDedupe(e,t){if(KC(t),t.count===0){this.dispatches=0;return}const r=gt(t.count,this.scope.workgroupSize,this.scope.caps),o=this.bindDedupe(t,r.stride??this.scope.workgroupSize);this.claim.dispatch(e,o.claim,r,[o.offset]),this.filter.dispatch(e,o.filter,r,[o.offset]),this.dispatches=2}bindDedupe(e,t){const r=this.scope.params(gs,{count:e.count,outIndex:e.outIndex,countIndex:e.countIndex,stride:t});return{claim:this.claim.bind({queue:e.queue,owner:e.owner,counters:e.counters,P:r.binding}),filter:this.filter.bind({queue:e.queue,owner:e.owner,out:e.out,outCount:e.outCount,P:r.binding}),offset:r.offset}}}const An=Object.freeze({frontierCount:0,nextFrontierCount:1,frontierDegreeSum:2,prevFrontierCount:3,prevDegreeSum:4,unvisitedCount:5,unvisitedDegreeSum:6,unvisitedListLen:7,edgeCount:8,edgeCountUnclamped:9,overflowLevels:10,level:11,visitedCount:12,switches:13,direction:14,done:15,arcsScanned:16,fusedLevels:17,twoPhaseLevels:18,bottomUpLevels:19,farCount:20,nextFarCount:21,thresholdBits:22,deltaBits:23,path:24,nextDegreeSum:25,stackTop:26,sigmaOverflow:27});function Pp(n){const e={};for(const[t,r]of Object.entries(n))r!==void 0&&(e[t]=r);return e}const xp=3;function Cp(n,e){if(!Number.isSafeInteger(e)||e<0)throw new S("E_INVALID_ARGUMENT",`frontier: ${n} must be a non-negative integer`,{argument:n,value:e,expected:"a non-negative integer"})}class XC{constructor(e,t,r,o,s){this.sideIndex=0,this.vertices=e,this.counters=t,this.edgeQueue=r,this.edgeCapacity=o,this.n=s}get side(){return this.sideIndex}get input(){return this.sideIndex===0?this.vertices[0]:this.vertices[1]}get output(){return this.sideIndex===0?this.vertices[1]:this.vertices[0]}swap(){this.sideIndex=this.sideIndex===0?1:0}reset(e,t,r){if(!Number.isInteger(t)||t<0||t>=this.n)throw new S("E_INVALID_ARGUMENT",`frontier: source ${t} is outside [0, ${this.n})`,{argument:"source",value:t,expected:`an integer in [0, ${this.n})`});const o=new ArrayBuffer(It.byteLength);It.write(new DataView(o),Pp(r)),this.sideIndex=0,e.writeBuffer(this.counters.buffer,this.counters.offset,o),e.writeBuffer(this.vertices[0].buffer,this.vertices[0].offset,Uint32Array.of(t))}}async function Np(n,e,t,r){Cp("n",e),Cp("arcCount",t);const o=r??Math.max(1,Math.min(t,Math.floor(n.caps.limits.maxStorageBufferBindingSize/4)));if(!Number.isSafeInteger(o)||o<1||o>Ve)throw new S("E_INVALID_ARGUMENT","frontier: edgeCapacity must be an integer >= 1",{argument:"edgeCapacity",value:o,expected:"an integer in [1, 2^32)"});const s=await n.pipelines.kernel(z("frontier-finalize")),i=4*Math.max(1,e),a=[{buffer:n.scratch(i,"frontier/vertices-0"),offset:0,size:i,window:null},{buffer:n.scratch(i,"frontier/vertices-1"),offset:0,size:i,window:null}],c={buffer:n.scratch(It.byteLength,"frontier/counters"),offset:0,size:It.byteLength,window:null},l={buffer:n.scratch(4*o,"frontier/edge-queue"),offset:0,size:4*o,window:null},u=new XC(a,c,l,o,e);return new QC(n,s,u)}class QC{constructor(e,t,r){this.scope=e,this.kernel=t,this.frontier=r}recordFinalize(e,t,r,o){if(!Number.isInteger(r)||r<0||r>=$e)throw new S("E_INVALID_ARGUMENT",`frontier: level ${r} is outside the submit`,{argument:"level",value:r,expected:`an integer in [0, ${$e})`});if(!Number.isInteger(t)||t<0||t>xp)throw new S("E_INVALID_ARGUMENT",`frontier: role ${t} is not a finalize role`,{argument:"role",value:t,expected:`an integer in [0, ${xp}]`});const{scope:s,frontier:i}=this,a=s.params(je,{...Pp(o),role:t,wg:s.workgroupSize,edgeCapacity:i.edgeCapacity,n:i.n}),c=this.kernel.bind({counters:i.counters,P:a.binding});this.kernel.dispatch(e,c,se(1,s.workgroupSize,s.caps),[a.offset])}}async function JC(n,e){const t=await n.pipelines.kernel(z("advance-expand",Ct(e,null)));return new ZC(n,e,t)}class ZC{constructor(e,t,r){this.scope=e,this.kernel=r,this.windows=El(t),this.n=ps(t,"advance")}record(e,t){if(t.n!==this.n)throw new S("E_INVALID_ARGUMENT",`advance: the frontier holds ${t.n} vertices, the core ${this.n} rows`,{argument:"frontier",value:t.n,expected:this.n});const{scope:r}=this,o=gt(t.n,r.workgroupSize,r.caps);for(const s of this.windows){const i=r.params(je,{wg:r.workgroupSize,edgeCapacity:t.edgeCapacity,n:t.n,arcBase:s.arcBase,arcEnd:s.arcEnd,stride:o.stride??r.workgroupSize}),a=this.kernel.bind({...on(s.core,null),frontierIn:t.input,counters:t.counters,edgeQueue:t.edgeQueue,P:i.binding});this.kernel.dispatch(e,a,o,[i.offset])}}}const Tp=8;function zi(n,e){return 4*Ii*Math.ceil(n/e)}async function Sl(n){const e=await n.pipelines.kernel(z("radix-hist")),t=await n.pipelines.kernel(z("radix-scatter")),r=await Or(n);return new tN(n,e,t,r)}function Ao(n,e,t){if(e.size<t)throw new S("E_INVALID_ARGUMENT",`radixSort: ${n} is smaller than ${t} bytes`,{argument:n,value:e.size,expected:t})}function eN(n,e,t,r,o,s){if(r!==8&&r!==16&&r!==24&&r!==32)throw new S("E_INVALID_ARGUMENT","radixSort: bits must be 8, 16, 24 or 32",{argument:"bits",value:r,expected:[8,16,24,32]});if(!Number.isSafeInteger(t)||t<0||t>Ve)throw new S("E_INVALID_ARGUMENT","radixSort: count must be a non-negative integer below 2^32",{argument:"count",value:t});const i=4*t;Ao("keys",n,i),Ao("vals",e,i),Ao("scratch.keys",o.keys,i),Ao("scratch.vals",o.vals,i);const a=zi(t,s);Ao("scratch.hist",o.hist,a),Ao("scratch.offsets",o.offsets,a)}class tN{constructor(e,t,r,o){this.dispatches=0,this.scope=e,this.hist=t,this.scatter=r,this.scan=o}get lastDispatches(){return this.dispatches}record(e,t,r,o,s,i){const a=this.scope.workgroupSize;if(eN(t,r,o,s,i,a),o===0)return this.dispatches=0,{keys:t,vals:r};const c=Math.ceil(o/a),l=se(o,a,this.scope.caps),u=Ii*c,d=4*u,f={...i.hist,size:d},h={...i.offsets,size:d};let g={keys:t,vals:r},w={keys:i.keys,vals:i.vals},p=0;const m=s/Tp;for(let y=0;y<m;y++){const b=this.scope.params(Al,{count:o,shift:Tp*y,groups:c,pad0:0}),v=this.hist.bind({keys:g.keys,hist:f,P:b.binding});this.hist.dispatch(e,v,l,[b.offset]),this.scan.record(e,f,u,h);const A=this.scatter.bind({keys:g.keys,vals:g.vals,offsets:h,keysOut:w.keys,valsOut:w.vals,P:b.binding});this.scatter.dispatch(e,A,l,[b.offset]),p+=2+this.scan.lastDispatches,[g,w]=[w,g]}return this.dispatches=p,g}}const tt="breadthFirstSearch",nN=128;function rN(n,e){return Math.max((5+4*n)*e+16,oN+n)}const oN=34;function sN(n){return n===void 0||Number.isNaN(n)||n>=Ve?Ve:Math.max(0,Math.ceil(n))}function iN(n,e){if(n===void 0)return null;if(n instanceof Uint32Array&&n.length===e&&n.buffer instanceof ArrayBuffer)return n;throw new S("E_INVALID_ARGUMENT",`${tt}: dest must be a Uint32Array of length ${e} over an ArrayBuffer`,{argument:"dest",value:`${n.constructor.name}(${n.length})`,expected:`Uint32Array(${e}) over an ArrayBuffer`})}function qt(n,e){return{buffer:n,offset:0,size:e,window:null}}function Op(n,e,t){const{bindings:r}=n.residency.view(e,t),{[t]:o}=r;if(o===void 0)throw new S("E_VALIDATION",`${tt}: the ${t} view has no ${t} binding`,{label:`${tt}/${t}`,message:`the ${t} view has no ${t} binding`});return o}function $p(n){return new S("E_ABORTED",`${tt}: the signal was aborted`,n===void 0?{}:{batchId:n})}function ys(n,e){const t=n[e];if(typeof t!="number")throw new S("E_VALIDATION",`${tt}: counters.${e} did not decode to a number`,{label:`${tt}/counters`,message:`the field ${e} did not decode to a number`});return t}async function Rp(n,e,t,r,o){n.assertReady(),await Lt(n);const s=e.nodeCount;if(!Number.isInteger(t)||t<0||t>=s)throw new S("E_INVALID_ARGUMENT",`${tt}: source ${t} is outside [0, ${s})`,{argument:"source",value:t,expected:`an integer in [0, ${s})`});const i=o.levelsPerSubmit??$e;if(!Number.isInteger(i)||i<1||i>$e)throw new S("E_INVALID_ARGUMENT",`${tt}: levelsPerSubmit must be an integer in [1, ${$e}]`,{argument:"levelsPerSubmit",value:i,expected:`an integer in [1, ${$e}]`});const a=iN(r?.dest,s),c=sN(r?.maxDepth),l=o.predKind??1;if(r?.signal?.aborted)throw $p();const u=n.residency.core(e),d=El(u);if(e.directed&&4*e.arcCount>n.caps.limits.maxStorageBufferBindingSize)throw new S("E_TOO_LARGE",`${tt}: the reverse adjacency of a directed snapshot (${4*e.arcCount} bytes) needs arc windows, which no view executes (spec 4.3); the bottom-up sweep binds it whole`,{needed:4*e.arcCount,limit:n.caps.limits.maxStorageBufferBindingSize,path:"windowed",algorithm:tt});const f=e.directed?Ui(n.residency.view(e,"reverse"),e.arcCount):u,h=El(f),g=Op(n,e,"outDegree"),w=Op(n,e,"inDegree"),p=Mt(n,tt,rN(d.length,i));o.onScope?.(p);try{const m=4*s,y=n.workgroupSize,b=qt(p.scratch(m,"depth"),m),v=Math.ceil(s/64)*64,A=Math.ceil(s/32),E=4*(v+A),I=qt(p.scratch(E,"sweep-in"),E),k={buffer:I.buffer,offset:0,size:m,window:null},N={buffer:I.buffer,offset:4*v,size:4*A,window:null},C=qt(p.scratch(m,"unvisited-flags"),m),O=qt(p.scratch(m,"iota"),m),T=qt(p.scratch(4,"compact-count"),4);await n.allocator.check();const $=await Np(p,s,e.arcCount,o.edgeCapacity),L=await JC(p,u),F=await Bi(p),M=await n.pipelines.kernel(z("bfs-contract")),R=await n.pipelines.kernel(z("bfs-fused",Ct(u,null))),D=await n.pipelines.kernel(z("bfs-bitset-build")),U=await n.pipelines.kernel(z("bfs-bottom-up",Ct(f,null))),B=await n.pipelines.kernel(z("bfs-unvisited-flags")),V=await n.pipelines.kernel(z("bfs-next-degree")),W=await n.pipelines.kernel(z("sssp-pred",{...Ct(u,null),MODE:1})),q=await n.pipelines.kernel(z("fill")),K=await Sl(p),{frontier:X}=$,{counters:H}=X,{queue:Y}=n.device,ee=se(s,y,n.caps),Z=gt(Math.max(s,X.edgeCapacity),y,n.caps),J=gt(s,y,n.caps),ce=gt(s,y,n.caps,nN),de=gt(s*y,y,n.caps),ne=se(A,y,n.caps),ve=(ot,st,dr,wu)=>{const ia=p.params(Ze,{count:s,value:dr,mode:wu,pad0:0});q.dispatch(ot,q.bind({dst:st,P:ia.binding}),ee,[ia.offset])},ue=gt(s,y,n.caps),we=ot=>{const st=p.params(je,{wg:y,n:s,stride:ue.stride??s}),dr=B.bind({inDegree:w,depth:b,flags:C,counters:H,P:st.binding});B.dispatch(ot,dr,ue,[st.offset]),F.record(ot,{queue:O,flags:C,count:s,out:k,outCount:T,outIndex:0})},Xe=ot=>(p.flush(),ot.submit()),he=new Pe(n,`${tt}/setup`),ge=he.pass("fill");ve(ge,b,x,0),ve(ge,O,0,1),he.endPass(),await Xe(he).readback,n.assertReady(),Y.writeBuffer(b.buffer,b.offset+4*t,Uint32Array.of(0)),X.reset(Y,t,{nextFrontierCount:1,level:Ve});const me={mode:{auto:0,"top-down":1,"bottom-up":2}[o.direction??"auto"],alpha:o.alpha??Dk,beta:o.beta??Lk,fusedMax:o.fusedMax??Rk,maxDepth:c};let De=0,Ne=0;for(;;){Y.writeBuffer(H.buffer,H.offset+4*An.unvisitedCount,new Uint32Array(3));const ot=new Pe(n,`${tt}/levels`),st=ot.pass("bfs");we(st);const dr=p.params(Ze,{count:A,value:0,mode:0,pad0:0}),wu=q.bind({dst:N,P:dr.binding});for(let fr=0;fr<i;fr++){$.recordFinalize(st,0,fr,{...me,firstOfSubmit:Math.min(fr,1)}),L.record(st,X),$.recordFinalize(st,1,fr,me);const $o=p.params(je,{wg:y,n:s,edgeCapacity:X.edgeCapacity,arcBase:0,arcEnd:e.arcCount,bitsBase:v,stride:Z.stride??y}),pu=M.bind({edgeQueue:X.edgeQueue,counters:H,depth:b,frontierOut:X.output,P:$o.binding});M.dispatch(st,pu,Z,[$o.offset]);for(const Lr of d){const Rs=p.params(je,{wg:y,n:s,edgeCapacity:X.edgeCapacity,arcBase:Lr.arcBase,arcEnd:Lr.arcEnd,stride:de.x*de.y}),mu=R.bind({...on(Lr.core,null),frontierIn:X.input,counters:H,depth:b,frontierOut:X.output,P:Rs.binding});R.dispatch(st,mu,de,[Rs.offset])}q.dispatch(st,wu,ne,[dr.offset]);const FD=D.bind({frontierIn:X.input,counters:H,bits:I,P:$o.binding});D.dispatch(st,FD,Z,[$o.offset]);for(const Lr of h){const Rs=p.params(je,{wg:y,n:s,arcBase:Lr.arcBase,arcEnd:Lr.arcEnd,bitsBase:v,stride:J.stride??y}),mu=U.bind({...on(Lr.core,null),sweepIn:I,counters:H,depth:b,frontierOut:X.output,P:Rs.binding});U.dispatch(st,mu,J,[Rs.offset])}const x0=p.params(je,{wg:y,n:s,stride:ce.stride??y}),BD=V.bind({frontier:X.output,outDegree:g,inDegree:w,counters:H,P:x0.binding});V.dispatch(st,BD,ce,[x0.offset]),X.swap()}ot.endPass();const ia=ot.readback(H.buffer,H.offset+4*An.done,4),aa=o.onLevel===void 0?null:{block:ot.readback(H.buffer,H.offset,It.byteLength),frontier:ot.readback(X.input.buffer,X.input.offset,X.input.size),count:ot.readback(T.buffer,T.offset,4)},P0=Xe(ot),ca=await P0.readback;if(De+=i,Ne+=1,n.assertReady(),r?.signal?.aborted)throw $p(P0.id);if(r?.onProgress?.(Math.min(De,s),s),aa!==null&&o.onLevel!==void 0){const fr=It.read(new DataView(ca),aa.block.offset),$o=new Uint32Array(ca,aa.frontier.offset,ys(fr,"nextFrontierCount")),pu=new Uint32Array(ca,aa.count.offset,1)[0];o.onLevel(De-1,fr,$o.slice(),pu)}if(new Uint32Array(ca,ia.offset,1)[0]!==0)break;if(Ne>s+1)throw new S("E_VALIDATION",`${tt}: the done flag never rose in ${Ne} submits (a traversal has at most ${s} levels)`,{label:tt,message:`the done flag never rose in ${Ne} submits`})}const He=qt(p.scratch(m,"order/keys"),m),_n=qt(p.scratch(m,"order/vals"),m),mt=zi(s,y),Ft={keys:qt(p.scratch(m,"order/keys-scratch"),m),vals:qt(p.scratch(m,"order/vals-scratch"),m),hist:qt(p.scratch(mt,"order/hist"),mt),offsets:qt(p.scratch(mt,"order/offsets"),mt)},Nt=qt(p.scratch(m,"parent"),m),Bt=new Pe(n,`${tt}/result`);Bt.copy(b,He,m);const Ae=Bt.pass("result");ve(Ae,_n,0,1);const yt=K.record(Ae,He,_n,s,32,Ft);ve(Ae,Nt,x,0);const Bn=gt(s,y,n.caps);for(const ot of d){const st=p.params(je,{wg:y,n:s,arcBase:ot.arcBase,arcEnd:ot.arcEnd,predKind:l,source:t,stride:Bn.stride??s}),dr=W.bind({...on(ot.core,null),dist:b,pred:Nt,P:st.binding});W.dispatch(Ae,dr,Bn,[st.offset])}Bt.endPass();const ur=Bt.readback(b.buffer,b.offset,m),ra=Bt.readback(Nt.buffer,Nt.offset,m),gu=Bt.readback(yt.vals.buffer,yt.vals.offset,m),MD=Bt.readback(H.buffer,H.offset,It.byteLength),oa=await Xe(Bt).readback;n.assertReady();const sa=It.read(new DataView(oa),MD.offset),$s=ys(sa,"visitedCount");if($s>s)throw new S("E_VALIDATION",`${tt}: visitedCount ${$s} exceeds the ${s} vertices (a duplicate claim)`,{label:`${tt}/visitedCount`,message:`the device counted ${$s} visits of ${s} vertices`});const k0=ys(sa,"level"),UD=ys(sa,"frontierCount")===0?k0:k0+1,S0=a??new Uint32Array(s);return S0.set(new Uint32Array(oa,ur.offset,s)),{depth:S0,parent:new Uint32Array(oa,ra.offset,s).slice(),order:new Uint32Array(oa,gu.offset,$s).slice(),visitedCount:$s,levels:UD,switches:ys(sa,"switches")}}finally{p.dispose()}}function aN(n,e,t,r){return Rp(n,e,t,r,{})}const Re="sssp",Dp=64,cN=4*$e+40;function Pl(n){return new Uint32Array(Float32Array.of(n).buffer)[0]}function kt(n,e){return{buffer:n,offset:0,size:e,window:null}}function sn(n,e){return new S("E_ABORTED",`${n}: the signal was aborted`,e===void 0?{}:{batchId:e})}function Lp(n,e,t){if(!Number.isInteger(e)||e<0||e>=t)throw new S("E_INVALID_ARGUMENT",`${n}: source ${e} is outside [0, ${t})`,{argument:"source",value:e,expected:`an integer in [0, ${t})`})}function xl(n,e){const t=n[e];if(typeof t!="number")throw new S("E_VALIDATION",`${Re}: counters.${e} did not decode to a number`,{label:`${Re}/counters`,message:`the field ${e} did not decode to a number`});return t}function Eo(n,e,t){if(e===void 0)return null;if(e instanceof Float32Array&&e.length===t&&e.buffer instanceof ArrayBuffer)return e;throw new S("E_INVALID_ARGUMENT",`${n}: dest must be a Float32Array of length ${t} over an ArrayBuffer`,{argument:"dest",value:`${e.constructor.name}(${e.length})`,expected:`Float32Array(${t}) over an ArrayBuffer`})}function Mp(n,e){if(e===void 0)return 1/0;if(Number.isNaN(e))throw new S("E_INVALID_ARGUMENT",`${n}: cutoff must not be NaN`,{argument:"cutoff",value:e,expected:"a number (the CPU port and the kernel would disagree on NaN)"});return e}function Up(n,e,t){if(t===void 0){if(e.weights===null)return null;let c=0;for(const l of e.weights)c+=l;return{values:e.weights,override:null,allOne:e.flags.allWeightsOne,nonNegative:e.flags.nonNegativeWeights,finite:e.flags.finiteWeights,sum:c}}if(t.length!==e.arcCount)throw new S("E_INVALID_ARGUMENT",`${n}: weights has ${t.length} entries, the snapshot ${e.arcCount} arcs`,{argument:"weights",value:t.length,expected:e.arcCount});const r=t instanceof Float32Array?t:Float32Array.from(t);let o=!0,s=!0,i=!0,a=0;for(const c of r)c!==1&&(o=!1),c<0&&(s=!1),Number.isFinite(c)||(i=!1),a+=c;return{values:r,override:r,allOne:o,nonNegative:s,finite:i,sum:a}}async function Fp(n,e,t,r,o,s){const i=r===1/0?void 0:Math.floor(r),a=await Rp(n,e,t,{maxDepth:i,signal:s?.signal,onProgress:s?.onProgress},{predKind:0}),c=o??new Float32Array(e.nodeCount);for(let l=0;l<e.nodeCount;l++){const u=a.depth[l];c[l]=u===x?1/0:u}return{dist:c,predArc:a.parent,reachedCount:a.visitedCount}}function Bp(n){return 2*Math.ceil(n/64)*64+64}async function zp(n){const{algorithm:e,ctx:t,scope:r,predKernel:o,recordFill:s,graph:i,dist:a,pred:c,n:l,arcCount:u,source:d,mode:f}=n,h=t.workgroupSize,{queue:g}=t.device,w=4*l,p=Math.ceil(l/64)*64,m={buffer:c.buffer,offset:c.offset,size:w,window:null};g.writeBuffer(c.buffer,c.offset+4*(p+d),Uint32Array.of(0)),g.writeBuffer(c.buffer,c.offset+8*p,new Uint32Array(2));const y=gt(l,h,t.caps),b={wg:h,n:l,arcBase:0,arcEnd:u,predKind:0,source:d,stride:y.stride??l,mode:f},v=Math.ceil((l+1)/$e)+1;let A=0;for(;;){const E=new Pe(t,`${e}/pred`),I=E.pass("pred"),k=(F,M)=>{const R=r.params(je,{...b,role:F,iteration:M}),D=o.bind({...i,dist:a,pred:c,P:R.binding});o.dispatch(I,D,y,[R.offset])};A===0&&f===0&&k(0,0);for(let F=0;F<$e;F++)k(1,F);s(I,m,l,x),k(2,0),E.endPass();const N=E.readback(a.buffer,a.offset,w),C=E.readback(c.buffer,c.offset,w),O=E.readback(c.buffer,c.offset+8*p,8);r.flush();const T=await E.submit().readback;t.assertReady(),A+=1;const[$,L]=new Uint32Array(T,O.offset,2);if($<$e)return{dist:new Float32Array(T,N.offset,l),predArc:new Uint32Array(T,C.offset,l).slice(),orphans:L};if(A>v)throw new S("E_VALIDATION",`${e}: the hop passes still changed something after ${A} batches (a hop count is at most ${l})`,{label:`${e}/pred`,message:`the hop passes did not converge in ${A} batches`});g.writeBuffer(c.buffer,c.offset+8*p,new Uint32Array(2))}}async function lN(n,e,t,r,o){n.assertReady(),await Lt(n);const s=e.nodeCount;Lp(Re,t,s);const i=o.roundsPerSubmit??$e;if(!Number.isInteger(i)||i<1||i>$e)throw new S("E_INVALID_ARGUMENT",`${Re}: roundsPerSubmit must be an integer in [1, ${$e}]`,{argument:"roundsPerSubmit",value:i,expected:`an integer in [1, ${$e}]`});if(o.delta!==void 0&&!(Number.isFinite(o.delta)&&o.delta>0))throw new S("E_INVALID_ARGUMENT",`${Re}: delta must be a finite positive number`,{argument:"delta",value:o.delta,expected:"a finite positive number"});const a=Eo(Re,r?.dest,s),c=Up(Re,e,r?.weights),l=Mp(Re,r?.cutoff);if(r?.signal?.aborted)throw sn(Re);if(c===null||c.allOne)return Fp(n,e,t,l,a,r);if(!c.nonNegative)throw new S("E_UNSUPPORTED",`${Re}: a negative weight has no shortest path here`,{feature:"sssp.negativeWeights",hint:"use bellmanFord"});if(!c.finite)throw new S("E_UNSUPPORTED",`${Re}: a NaN or infinite weight has no bit-pattern order`,{feature:"sssp.nonFiniteWeights"});const{arcCount:u}=e,d=n.residency.core(e),f=n.caps.limits.maxStorageBufferBindingSize;sr(d,u,f,Re);const h=Math.ceil(Math.max(1,u)/Dp)*Dp;if(8*h>f)throw new S("E_TOO_LARGE",`${Re}: the near-far queue of ${h} entries per half needs ${8*h} bytes, above the ${f}-byte binding limit (the relax is never windowed)`,{needed:8*h,limit:f,path:"sssp.queue",algorithm:Re});const g=Math.fround(o.delta??(c.sum===0?1:Mk*(c.sum/u)/(u/s))),w=Pl(g),p=s+Math.ceil(c.sum/g)+1,m=Math.ceil((p+1)/i)+1,y=Mt(n,Re,cN);try{const b=n.workgroupSize,v=4*s,A=kt(y.scratch(v,"dist"),v),E=kt(y.scratch(v,"owner"),v),I=kt(y.scratch(8*h,"queue-out"),8*h),k={buffer:I.buffer,offset:0,size:4*h,window:null},N={buffer:I.buffer,offset:4*h,size:4*h,window:null},C=Bp(s),O=kt(y.scratch(4*C,"pred"),4*C),{queue:T}=n.device;let $;if(c.override!==null){const he=y.scratch(4*u,"weights");T.writeBuffer(he,0,c.override),$=kt(he,4*u)}await n.allocator.check();const L=await Np(y,s,u,h),F=await Bi(y),M=Ct(d,null,$),R=await n.pipelines.kernel(z("sssp-relax",M)),D=await n.pipelines.kernel(z("sssp-pred",{...M,MODE:0})),U=await n.pipelines.kernel(z("fill")),B=on(d,null,$),{frontier:V}=L,{counters:W}=V,q=V.vertices[0],K=V.vertices[1],X=(he,ge,me,De)=>{const Ne=y.params(Ze,{count:me,value:De,mode:0,pad0:0});U.dispatch(he,U.bind({dst:ge,P:Ne.binding}),se(me,b,n.caps),[Ne.offset])},H=he=>(y.flush(),he.submit()),Y=new Pe(n,`${Re}/setup`),ee=Y.pass("fill");X(ee,A,s,ho),X(ee,O,C,x),Y.endPass(),await H(Y).readback,n.assertReady(),T.writeBuffer(A.buffer,A.offset+4*t,Uint32Array.of(0)),V.reset(T,t,{nextFrontierCount:1,thresholdBits:w,deltaBits:w}),T.writeBuffer(I.buffer,I.offset,Uint32Array.of(t));const Z={queue:k,count:h,countIndex:An.edgeCount,counters:W,owner:E,out:q,outCount:W,outIndex:An.frontierCount},J={queue:N,count:h,countIndex:An.edgeCountUnclamped,counters:W,owner:E,out:K,outCount:W,outIndex:An.farCount},ce=gt(s,b,n.caps),de={wg:b,n:s,edgeCapacity:h,arcBase:0,arcEnd:u,cutoffBits:Pl(l),source:t,stride:ce.stride??b};let ne=0,ve=0;for(;;){const he=new Pe(n,`${Re}/rounds`),ge=he.pass("sssp"),me=y.params(je,{...de,role:0}),De=y.params(je,{...de,role:1}),Ne=R.bind({...B,dist:A,counters:W,queueIn:q,queueOut:I,P:me.binding}),He=R.bind({...B,dist:A,counters:W,queueIn:K,queueOut:I,P:De.binding});for(let Ae=0;Ae<i;Ae++)L.recordFinalize(ge,2,Ae,{}),F.recordDedupe(ge,Z),F.recordDedupe(ge,J),L.recordFinalize(ge,3,Ae,{}),R.dispatch(ge,Ne,ce,[me.offset]),R.dispatch(ge,He,ce,[De.offset]);he.endPass();const _n=he.readback(W.buffer,W.offset+4*An.done,4),mt=o.onRound===void 0?null:he.readback(W.buffer,W.offset,It.byteLength),Ft=H(he),Nt=await Ft.readback;if(ne+=i,ve+=1,n.assertReady(),r?.signal?.aborted)throw sn(Re,Ft.id);r?.onProgress?.(Math.min(ne,p),p),mt!==null&&o.onRound!==void 0&&o.onRound(ne-1,It.read(new DataView(Nt),mt.offset));const Bt=new Uint32Array(Nt,_n.offset,1)[0];if(Bt===1)break;if(Bt!==0){const Ae=It.read(new DataView(await n.readback.read(W.buffer,It.byteLength,void 0,W.offset)));if(Bt===2){const yt=Math.max(xl(Ae,"nextFrontierCount"),xl(Ae,"nextFarCount"));throw new S("E_TOO_LARGE",`${Re}: a raw pile of ${yt} entries overflowed its ${h}-entry half`,{needed:yt,limit:h,path:"sssp.pile",algorithm:Re})}throw new S("E_UNSUPPORTED",`${Re}: the f32 threshold ${xl(Ae,"thresholdBits")} absorbed the delta ${w} (as bit patterns); the far pile can no longer be bucketed`,{feature:"sssp.thresholdAbsorbed",hint:"the distances outgrew the delta's f32 precision"})}if(ve>m)throw new S("E_VALIDATION",`${Re}: the done flag never rose in ${ve} submits (at most ${p} rounds)`,{label:`${Re}/rounds`,message:`the done flag never rose in ${ve} submits`})}const ue=await zp({algorithm:Re,ctx:n,scope:y,predKernel:D,recordFill:X,graph:B,dist:A,pred:O,n:s,arcCount:u,source:t,mode:0});if(ue.orphans!==0)throw new S("E_VALIDATION",`${Re}: ${ue.orphans} reached node(s) the predecessor key never reached (a kernel bug)`,{label:`${Re}/pred`,message:`${ue.orphans} orphan(s) in the predecessor pass`});const we=a??new Float32Array(s);we.set(ue.dist);let Xe=0;for(const he of we)he!==1/0&&(Xe+=1);return{dist:we,predArc:ue.predArc,reachedCount:Xe}}finally{y.dispose()}}function Gp(n,e,t,r){return lN(n,e,t,r,{})}const ir="allPairsShortestPath",_o=Math.floor(Wk/3);function Wp(n){const e=n.maxStorageBufferBindingSize,t=n.maxBufferSize,r=t<e?"maxBufferSize":"maxStorageBufferBindingSize",o=Math.min(e,t);let s=Math.floor(Math.sqrt(o/4));for(;4*s*s>o;)s-=1;for(;4*(s+1)*(s+1)<=o;)s+=1;return{maxNodes:s,limit:o,limitName:r}}async function Vp(n,e,t,r,o,s,i){const a=e.nodeCount,c=n.residency.core(e);sr(c,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,i);const l=Math.ceil(a/il),u=n.workgroupSize,d=4*a*a,f=kt(t.scratch(d,"dist"),d);await n.allocator.check();const h=r?void 0:null,g=await n.pipelines.kernel(z("fill")),w=await n.pipelines.kernel(z("apsp-init",Ct(c,null,h))),p=await Promise.all([0,1,2].map(v=>n.pipelines.kernel(z("apsp-fw",{PHASE:v})))),m=on(c,null,h),y=l-1,b=[mo(1,n.caps),mo(2*y,n.caps),mo(y*y,n.caps)];for(let v=0;v<l;v+=o){const A=new Pe(n,`${i}/sweep`),E=A.pass("apsp");if(v===0){const N=t.params(Ze,{count:a*a,value:ho,mode:0,pad0:0});g.dispatch(E,g.bind({dst:f,P:N.binding}),se(a*a,u,n.caps),[N.offset]);const C=t.params(Ri,{n:a,round:0,blocks:l,infBits:ho});w.dispatch(E,w.bind({...m,dist:f,P:C.binding}),se(a,u,n.caps),[C.offset])}const I=Math.min(v+o,l);for(let N=v;N<I;N++){const C=t.params(Ri,{n:a,round:N,blocks:l,infBits:ho});for(let O=0;O<3;O++){const T=p[O];T.dispatch(E,T.bind({dist:f,P:C.binding}),b[O],[C.offset])}}A.endPass(),t.flush();const k=A.submit();if(await k.readback,n.assertReady(),s?.onProgress?.(I,l),s?.signal?.aborted)throw sn(i,k.id)}return f}async function uN(n,e,t,r){n.assertReady();const o=e.nodeCount,s=r.roundsPerSubmit??_o;if(!Number.isInteger(s)||s<1||s>_o)throw new S("E_INVALID_ARGUMENT",`${ir}: roundsPerSubmit must be an integer in [1, ${_o}]`,{argument:"roundsPerSubmit",value:s,expected:`an integer in [1, ${_o}]`});const{maxNodes:i,limit:a,limitName:c}=Wp(n.caps.limits);if(o>i)throw new S("E_TOO_LARGE",`${ir}: ${o} nodes need a ${4*o*o}-byte distance matrix in one storage binding; this device's ${c} of ${a} bytes holds at most ${i} nodes -- raise it through GpuContextOptions.limits`,{needed:4*o*o,limit:a,path:"allPairs.matrix",algorithm:ir,nodes:o,maxNodes:i,limitName:c,hint:`raise ${c} through GpuContextOptions.limits`});const l=Eo(ir,t?.dest,o*o)??new Float32Array(o*o),u=e.weights!==null&&e.weights!==null&&!e.flags.allWeightsOne;if(u&&!e.flags.nonNegativeWeights)throw new S("E_UNSUPPORTED",`${ir}: a negative weight is not supported`,{feature:"allPairs.negativeWeights",hint:"the blocked Floyd-Warshall sweep needs non-negative weights; pass weighted: false for hop counts"});if(u&&!e.flags.finiteWeights)throw new S("E_UNSUPPORTED",`${ir}: a NaN or infinite weight has no shortest path`,{feature:"allPairs.nonFiniteWeights"});if(o===0)return{dist:l,n:o};await Lt(n);const d=Mt(n,ir,Math.min(s,Math.ceil(o/il))+2);try{const f=await Vp(n,e,d,u,s,t,ir),h=4*o*o;return await n.readback.read(f.buffer,h,l),n.assertReady(),{dist:l,n:o}}finally{d.dispose()}}function dN(n,e,t){return uN(n,e,t,{})}const nt="bellmanFord",fN=8,hN=16,gN=$e+16;function wN(n,e){const{arcToEdge:t,edgeToArc:r}=n;for(let o=0;o<n.arcCount;o++){const s=r[t[o]];if(e[o]!==e[s])throw new S("E_UNSUPPORTED",`${nt}: weights[${o}] = ${e[o]} differs from weights[${s}] = ${e[s]}, the forward arc of the same undirected edge; the kernel reads one weight per edge`,{feature:"bellmanFord.asymmetricUndirectedWeights",hint:"use a directed snapshot"})}}async function pN(n,e,t,r,o){n.assertReady(),await Lt(n);const s=e.nodeCount;Lp(nt,t,s);const i=o.maxRetries??hN;if(!Number.isInteger(i)||i<1)throw new S("E_INVALID_ARGUMENT",`${nt}: maxRetries must be an integer >= 1`,{argument:"maxRetries",value:i,expected:"an integer >= 1"});const a=o.roundsPerBatch??fN;if(!Number.isInteger(a)||a<1||a>$e)throw new S("E_INVALID_ARGUMENT",`${nt}: roundsPerBatch must be an integer in [1, ${$e}]`,{argument:"roundsPerBatch",value:a,expected:`an integer in [1, ${$e}]`});const c=Eo(nt,r?.dest,s),l=Up(nt,e,r?.weights),u=Mp(nt,r?.cutoff);if(r?.signal?.aborted)throw sn(nt);if(l===null||l.allOne)return{result:{...await Fp(n,e,t,u,c,r),hasNegativeCycle:!1},rounds:0,retryExhaustedRounds:0};if(!l.finite)throw new S("E_UNSUPPORTED",`${nt}: a NaN or infinite weight has no shortest path`,{feature:"bellmanFord.nonFiniteWeights"});!e.directed&&l.override!==null&&wN(e,l.override);const{arcCount:d}=e,f=n.residency.core(e,["rowPtr","colIdx","weights","edgeToArc"]);sr(f,d,n.caps.limits.maxStorageBufferBindingSize,nt);const h=n.residency.view(e,"edgeList"),g=h.scalars.edgeCount[0],w=Mt(n,nt,gN);try{const p=n.workgroupSize,m=4*s,y=kt(w.scratch(m,"dist"),m),b=Bp(s),v=kt(w.scratch(4*b,"pred"),4*b),A=kt(w.scratch(ws.byteLength,"flags"),ws.byteLength);let E=null,{edgeToArc:I}=f;I===null&&(E=kt(w.scratch(4*g,"iota"),4*g),I=E);const{queue:k}=n.device;let N;if(l.override!==null){const J=w.scratch(4*d,"weights");k.writeBuffer(J,0,l.override),N=kt(J,4*d)}await n.allocator.check();const C=Ct(f,null,N),O=await n.pipelines.kernel(z("bf-relax",{UNDIRECTED:!e.directed})),T=await n.pipelines.kernel(z("sssp-pred",{...C,MODE:0})),$=await n.pipelines.kernel(z("fill")),L=on(f,null,N),F=(J,ce,de,ne,ve=0)=>{const ue=w.params(Ze,{count:de,value:ne,mode:ve,pad0:0});$.dispatch(J,$.bind({dst:ce,P:ue.binding}),se(de,p,n.caps),[ue.offset])},M=J=>(w.flush(),J.submit()),R=new Pe(n,`${nt}/setup`),D=R.pass("fill");F(D,y,s,ho),F(D,v,b,x),E!==null&&F(D,E,g,0,1),R.endPass(),await M(R).readback,n.assertReady(),k.writeBuffer(y.buffer,y.offset+4*t,Uint32Array.of(0));const U=gt(g,p,n.caps),B={edgeSrc:h.bindings.src,edgeDst:h.bindings.dst,edgeToArc:I,weights:L.weights,dist:y,flags:A},V={edgeCount:g,stride:U.stride??g,maxRetries:i,cutoffBits:Pl(u)},W=new Uint32Array(ws.byteLength/4),q=async(J,ce)=>{k.writeBuffer(A.buffer,A.offset,W);const de=new Pe(n,`${nt}/${ce}`),ne=de.pass("relax"),ve=w.params(yp,V),ue=O.bind({...B,P:ve.binding});for(let me=0;me<J;me++)O.dispatch(ne,ue,U,[ve.offset]);de.endPass();const we=de.readback(A.buffer,A.offset,ws.byteLength),Xe=M(de),he=await Xe.readback;n.assertReady();const ge=ws.read(new DataView(he),we.offset);return{changed:Number(ge.changed),retryExhausted:Number(ge.retryExhausted),id:Xe.id}};let K=0,X=0,H=!1;for(;;){const J=s-1-K;if(J<=0){const ne=await q(1,"decision");if(ne.retryExhausted!==0)throw new S("E_VALIDATION",`${nt}: a lane exhausted the ${i}-retry compare-exchange bound in the decision round, so its change is not a verdict`,{label:`${nt}/retry`,message:"retryExhausted in the decision round",batchId:ne.id});H=ne.changed!==0;break}const ce=Math.min(a,J),de=await q(ce,"rounds");if(K+=ce,de.retryExhausted!==0&&(X+=1),r?.signal?.aborted)throw sn(nt,de.id);if(r?.onProgress?.(K,s),de.changed===0&&de.retryExhausted===0)break}const Y=await zp({algorithm:nt,ctx:n,scope:w,predKernel:T,recordFill:F,graph:L,dist:y,pred:v,n:s,arcCount:d,source:t,mode:1});if(Y.orphans!==0&&!H)throw new S("E_UNSUPPORTED",`${nt}: ${Y.orphans} reached node(s) the tight subgraph never reaches (a cycle of weights below one f32 ulp relaxed once)`,{feature:"bellmanFord.roundedCycle",hint:"a cycle of weights below one f32 ulp relaxed once at a distance above 2^24; scale the weights or shorten the distances"});const ee=c??new Float32Array(s);ee.set(Y.dist);let Z=0;for(const J of ee)J!==1/0&&(Z+=1);return{result:{dist:ee,predArc:Y.predArc,reachedCount:Z,hasNegativeCycle:H},rounds:K,retryExhaustedRounds:X}}finally{w.dispose()}}async function mN(n,e,t,r){return(await pN(n,e,t,r,{})).result}class yN{constructor(e,t,r,o,s){this.dispatches=0,this.scope=e,this.tiers=t,this.perm=r,this.weights=o,this.hasWeights=s}get lastDispatches(){return this.dispatches}record(e,t,r,o){const{HAS_WEIGHTS:s}=Ct(t,this.perm,this.weights);if(s!==this.hasWeights)throw new S("E_INVALID_ARGUMENT","spmvPull: the core's weights pattern differs from the one prepared",{argument:"rev",value:s,expected:this.hasWeights});const i=ps(t,"spmvPull"),a=this.scope.workgroupSize;this.dispatches=0;for(const{tier:c,kernel:l,start:u,end:d}of this.tiers){const f=c===0?i:d,h=f-u;if(h<=0)continue;const g=c===2?1:a/Mn,w=c===0?gt(h,a,this.scope.caps):se(h,g,this.scope.caps);if(w.x===0)continue;const p=this.scope.params(pp,{n:f,arcBase:0,arcEnd:Li(t),stride:w.stride??h,alpha:o.alpha,beta:o.beta,uniformP:o.uniformP,start:u}),m=l.bind({...on(t,this.perm,this.weights),xNorm:r.xNorm,rankOut:r.rankOut,personalization:r.personalization??r.xNorm,partials:r.partials,P:p.binding});l.dispatch(e,m,w,[p.offset]),this.dispatches++}}}async function Cl(n,e,t){BC(e,"spmvPull");const{tiers:r}=t,o=r?.perm??null;if(r!==null&&n.workgroupSize<Mn)throw new S("E_UNSUPPORTED",`spmvPull: the mid tier folds ${Mn} lanes per row, more than the workgroup size ${n.workgroupSize}`,{feature:"spmvPull.tiers"});const s=r===null?[{tier:0,start:0,end:ps(e,"spmvPull")}]:[{tier:2,start:0,end:r.segmentOffsets[1]},{tier:1,start:r.segmentOffsets[1],end:r.segmentOffsets[2]},{tier:0,start:r.segmentOffsets[2],end:r.segmentOffsets[4]}],i=[];for(const c of s){if(c.tier!==0&&c.end<=c.start)continue;const l=z("spmv-pull",{...Ct(e,o,t.weights),HAS_PERSONALIZATION:t.personalization,USE_DANGLING:t.dangling,TIER:c.tier});i.push({...c,kernel:await n.pipelines.kernel(l)})}const{HAS_WEIGHTS:a}=Ct(e,o,t.weights);return new yN(n,i,o,t.weights,a)}const jp=8,bN=4*jp+8;function vN(n,e,t){if(n===void 0)return null;if(n instanceof Float32Array&&n.length===e&&n.buffer instanceof ArrayBuffer)return n;throw new S("E_INVALID_ARGUMENT",`${t}: dest must be a Float32Array of length ${e} over an ArrayBuffer`,{argument:"dest",value:`${n.constructor.name}(${n.length})`,expected:`Float32Array(${e}) over an ArrayBuffer`})}function qp(n,e,t){const r=n.residency.core(e);return sr(r,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,t),r}function Nl(n,e){n.residency.core(e,["rowPtr"]);const t=n.residency.view(e,"reverse");return Ui(t,t.scalars.arcCount[0])}function Hp(n,e){return new S("E_ABORTED",`${n}: the signal was aborted`,e===void 0?{}:{batchId:e})}function Tl(n,e){return{buffer:n,offset:0,size:e,window:null}}async function Gi(n,e,t){await Lt(n);const r=Mt(n,t.label,bN);try{const o=4*e,s=(t.alternate===null?["rankA","rankB"]:["rankA","rankB","rankC"]).map(E=>Tl(r.scratch(o,E),o)),i=Tl(r.scratch(o,"xNorm"),o),a=se(e,n.workgroupSize,n.caps),c=yl(a),l=et.byteLength*(1+c),u=r.scratch(l,"partials"),d=Tl(u,l);await n.allocator.check();const f={personalization:!1,dangling:!1,weights:t.weights,tiers:null},h=[{core:t.adjacency,pull:await Cl(r,t.adjacency,f)}];t.alternate!==null&&h.push({core:t.alternate,pull:await Cl(r,t.alternate,f)});const g=await n.pipelines.kernel(z("pr-scale",{NORM_MODE:t.normMode})),w=t.normMode===4?null:await n.pipelines.kernel(z("pr-scale",{NORM_MODE:3})),p=await n.pipelines.kernel(z("pr-finalize",{NORM_MODE:t.normMode})),m=se(1,n.workgroupSize,n.caps),{queue:y}=n.device;y.writeBuffer(s[0].buffer,0,new Float32Array(e).fill(1/e));for(const E of s.slice(1))y.writeBuffer(E.buffer,0,new Float32Array(e));const b=new ArrayBuffer(et.byteLength);et.write(new DataView(b),{firstConverged:Ve,iteration:0}),y.writeBuffer(u,0,b);const v={alpha:t.alpha,beta:t.beta,uniformP:t.uniformP};let A=0;for(;;){const E=Math.min(jp,t.maxIterations-A),I=new Pe(n,t.label),k=I.pass("iterations"),N=A+E===t.maxIterations;for(let D=0;D<E+(N?1:0);D++){const U=A+D+1,B=r.params(Ti,{n:e,groups:c,iteration:U,trackConvergence:1,convergeThreshold:t.tolerance*e}),V=s[(U-1)%s.length],W=s[U%s.length],{core:q,pull:K}=h[(U-1)%h.length],X={rankIn:V,rankPrev:W,outWeightSum:V,xNorm:i,partials:d,P:B.binding};if(g.dispatch(k,g.bind(X),a,[B.offset]),p.dispatch(k,p.bind({partials:d,P:B.binding}),m,[B.offset]),D===E)break;w!==null&&w.dispatch(k,w.bind(X),a,[B.offset]),K.record(k,q,{xNorm:i,rankOut:W,personalization:null,partials:d},v)}I.endPass();const C=I.readback(u,0,et.byteLength),O=I.readback(s[(A+E)%s.length].buffer,0,o),T=t.alternate===null?null:I.readback(s[(A+E-1)%s.length].buffer,0,o);r.flush();const $=I.submit(),L=await $.readback;if(A+=E,n.assertReady(),t.signal?.aborted===!0)throw Hp(t.label,$.id);t.onProgress?.(A,t.maxIterations);const M=et.read(new DataView(L),C.offset).firstConverged,R=M!==Ve;if(R||A>=t.maxIterations)return R&&A<t.maxIterations&&t.onProgress?.(t.maxIterations,t.maxIterations),{scores:new Float32Array(L,O.offset,e).slice(),previous:T===null?null:new Float32Array(L,T.offset,e).slice(),iterations:R?M:A,converged:R,iterationsRun:A}}}finally{r.dispose()}}const wt="betweennessCentrality",AN=16,EN=2654435769,_N=Math.max(3*$e,Pi)+16;function Kp(n,e,t){const r=4*(n+2);if(r>t.maxStorageBufferBindingSize)throw new S("E_TOO_LARGE",`${wt}: one source needs ${r} bytes in its largest binding at n = ${n}, above maxStorageBufferBindingSize = ${t.maxStorageBufferBindingSize}; a limit of at least ${r} admits one source per batch`,{needed:r,limit:t.maxStorageBufferBindingSize,path:"binding",algorithm:wt});const o=Math.floor(t.maxStorageBufferBindingSize/(4*n)),s=Math.floor(Uk*t.maxBufferSize/(AN*n));return Math.max(1,Math.min(o,s,Fk,e))}function IN(n,e){const t=Array.from({length:n},(o,s)=>s);let r=EN;for(let o=0;o<e;o++){r=r+1831565813>>>0;let s=Math.imul(r^r>>>15,r|1);s=s+Math.imul(s^s>>>7,s|61)^s;const i=((s^s>>>14)>>>0)/2**32,a=o+Math.floor(i*(n-o));[t[o],t[a]]=[t[a],t[o]]}return t.slice(0,e)}function Wi(n,e,t){return new S("E_INVALID_ARGUMENT",`${wt}: ${n} must be ${t}`,{argument:n,value:e,expected:t})}function Yp(n,e){const t=n?.k;if(t!==void 0&&(!Number.isInteger(t)||t<0||t>e))throw Wi("k",t,`an integer in [0, ${e}]`);const r=n?.sources;if(r!==void 0){for(const o of r)if(!Number.isInteger(o)||o<0||o>=e)throw Wi("sources",o,`node indices in [0, ${e})`);if(t!==void 0&&t!==r.length)throw Wi("k",t,`absent or equal to sources.length (${r.length})`);return[...r]}return t!==void 0?IN(e,t):Array.from({length:e},(o,s)=>s)}async function Xp(n,e,t,r,o,s){const i=s,[a,c,l]=await Promise.all(["bc-finalize","bc-forward","bc-backward"].map(h=>n.pipelines.kernel(z(h,{SCALED:i})))),u=r?await n.pipelines.kernel(z("bc-forward-edge",{UNDIRECTED:!e.directed,SCALED:i})):null,d=o?await n.pipelines.kernel(z("bc-edge-gather",{SCALED:i})):null;let f=null;if(s){const h=e.directed?Nl(n,e):t;f={kernel:await n.pipelines.kernel(z("bc-count")),rowPtr:h.rowPtr,colIdx:h.colIdx??h.rowPtr}}return{finalize:a,forward:c,forwardEdge:u,backward:l,edgeGather:d,count:f}}function Io(n,e,t,r,o){const{scope:s,fill:i,ctx:a}=n,c=s.params(Ze,{count:r,value:o,mode:0,pad0:0});i.dispatch(e,i.bind({dst:t,P:c.binding}),se(r,a.workgroupSize,a.caps),[c.offset])}function ar(n,e,t,r,o,s,i){const{scope:a,ctx:c}=n,l=gt(s,c.workgroupSize,c.caps,i),u=a.params(or,{...o,stride:l.stride??0});let d=n.bound.get(t);d===void 0&&(d=t.bind({...r,P:u.binding}),n.bound.set(t,d)),t.dispatch(e,d,s===0?se(1,c.workgroupSize,c.caps):l,[u.offset])}async function Vi(n,e,t){n.scope.flush();const r=e.submit(),o=await r.readback;if(n.ctx.assertReady(),t?.aborted)throw sn(wt,r.id);return o}async function Qp(n,e,t,r,o,s,i){const{ctx:a,n:c,S:l,ends:u,levelMax:d,depthK:f,sigmaK:h,deltaK:g,counters:w}=n,p=t.length,m=c*p,y=Uint32Array.from(t,(O,T)=>T*c+O);a.device.queue.writeBuffer(l.buffer,l.offset,y);const b={n:c,k:p,count:r==="edge"?n.edgeCount:0},v=r==="edge"?n.edgeCount:m;let A=0,E=0,I=!1,k=null;for(let O=!0;k===null;O=!1){const T=new Pe(a,`${wt}/forward`),$=T.pass("forward");O&&(Io(n,$,f,m,4294967295),Io(n,$,h,m,0),Io(n,$,g,m,0),e.count!==null&&Io(n,$,d,c+2,0),ar(n,$,e.finalize,{counters:w,ends:u,S:l,depthK:f,sigmaK:h,levelMax:d},{n:c,k:p,role:1},1));for(let U=0;U<o;U++)if(ar(n,$,e.finalize,{counters:w,ends:u,S:l,depthK:f,sigmaK:h,levelMax:d},{n:c,k:p,role:0},1),r==="edge"&&e.forwardEdge!==null&&n.edgeSrc!==null&&n.edgeDst!==null?ar(n,$,e.forwardEdge,{edgeSrc:n.edgeSrc,edgeDst:n.edgeDst,S:l,ends:u,counters:w,depthK:f,sigmaK:h},b,v):ar(n,$,e.forward,{rowPtr:n.rowPtr,colIdx:n.colIdx,S:l,ends:u,counters:w,depthK:f,sigmaK:h},b,v),e.count!==null){const{kernel:B,rowPtr:V,colIdx:W}=e.count;ar(n,$,B,{rowPtr:V,colIdx:W,S:l,ends:u,counters:w,depthK:f,sigmaK:h,levelMax:d},{n:c,k:p},m,Gk)}A+=o,T.endPass();const L=Math.min(c+2,A+1),F=T.readback(w.buffer,w.offset,It.byteLength),M=T.readback(u.buffer,u.offset,4*L),R=await Vi(n,T,i),D=new Uint32Array(R,F.offset,It.byteLength/4);if(D[An.done]!==0){if(E=D[An.level],I=D[An.sigmaOverflow]!==0,k=new Uint32Array(R,M.offset,L).slice(0,E+1),I&&e.count===null)return{levels:E,wrapped:!0,overflow:!1}}else if(A>c+2)throw new S("E_VALIDATION",`${wt}: the done flag never rose in ${A} levels`,{label:wt,message:`the done flag never rose in ${A} levels`})}const N=[];for(let O=E-1;O>=1;O--)N.push(O);let C=null;for(let O=0;;O+=Pi){const T=N.slice(O,O+Pi),$=O+Pi>=N.length,L=new Pe(a,`${wt}/backward`),F=L.pass("backward");for(const U of T){const B=k[U],V=k[U+1]-B;ar(n,F,e.backward,{rowPtr:n.rowPtr,colIdx:n.colIdx,S:l,depthK:f,sigmaK:h,deltaK:g,levelMax:d},{n:c,k:p,start:B,count:V},V)}$&&(ar(n,F,n.gather,{deltaK:g,bc:n.bc},{n:c,k:p},c),e.edgeGather!==null&&n.arcScores!==null&&ar(n,F,e.edgeGather,{rowPtr:n.rowPtr,colIdx:n.colIdx,depthK:f,sigmaK:h,deltaK:g,arcScores:n.arcScores,levelMax:d},{n:c,k:p,count:n.arcCount},n.arcCount)),L.endPass();const M=$&&s.readArrays===!0,R=M?[f,h,g].map(U=>L.readback(U.buffer,U.offset,4*m)):[],D=await Vi(n,L,i);if(M&&(C={depthK:new Uint32Array(D,R[0].offset,m).slice(),sigmaK:new Uint32Array(D,R[1].offset,m).slice(),deltaK:new Float32Array(D,R[2].offset,m).slice()}),$)break}return s.onBatch?.({sources:t,forward:r,levels:E,ends:k.slice(),scaled:e.count!==null,sigmaOverflow:I,depthK:C?.depthK??null,sigmaK:C?.sigmaK??null,deltaK:C?.deltaK??null}),{levels:E,wrapped:!1,overflow:I}}async function Jp(n,e,t,r,o,s){const i=e.nodeCount,a=o.forward??"auto",c=o.levelsPerSubmit??$e;if(!Number.isInteger(c)||c<1||c>$e)throw Wi("levelsPerSubmit",c,`an integer in [1, ${$e}]`);const l=o.limits??n.caps.limits,u=Kp(i,t.length,l),d=n.residency.core(e);sr(d,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,wt);const{edgeCount:f}=e,g=(a==="edge"||a==="auto"&&t.length>u)&&f>0?n.residency.view(e,"edgeList"):null,w=Mt(n,wt,_N);try{const p=4*i*u,m=(M,R)=>kt(w.scratch(M,R),M),y=4*Math.max(1,e.arcCount),[b,v]=await Promise.all(["fill","bc-gather"].map(M=>n.pipelines.kernel(z(M)))),A=await Xp(n,e,d,g!==null,r,!1),E={ctx:n,scope:w,n:i,S:m(p,"S"),ends:m(4*(i+2),"ends"),levelMax:m(4*(i+2),"level-max"),depthK:m(p,"depthK"),sigmaK:m(p,"sigmaK"),deltaK:m(p,"deltaK"),counters:m(It.byteLength,"counters"),bc:m(4*i,"bc"),arcScores:r?m(y,"arc-scores"):null,rowPtr:d.rowPtr,colIdx:d.colIdx??d.rowPtr,edgeSrc:g?.bindings.src??null,edgeDst:g?.bindings.dst??null,edgeCount:f,arcCount:e.arcCount,fill:b,gather:v,exact:A,scaled:null,bound:new Map};await n.allocator.check();const I=new Pe(n,`${wt}/setup`),k=I.pass("setup");Io(E,k,E.bc,i,0),E.arcScores!==null&&Io(E,k,E.arcScores,y/4,0),I.endPass(),await Vi(E,I,s?.signal);let N=!1,C=0,O=-1;for(let M=0;M<t.length;){const R=Kp(i,t.length-M,l);let D=a==="edge"?"edge":"frontier";a==="auto"&&O>=0&&(D=O<Bk*Math.log2(i)?"edge":"frontier"),E.exact.forwardEdge===null&&(D="frontier");const U=t.slice(M,M+R);let B=await Qp(E,E.scaled??E.exact,U,D,c,o,s?.signal);B.wrapped&&(E.scaled??=await Xp(n,e,d,g!==null,r,!0),B=await Qp(E,E.scaled,U,D,c,o,s?.signal)),N=N||B.overflow,O=B.levels,M+=R,C+=1,s?.onProgress?.(M,t.length)}const T=new Pe(n,`${wt}/result`),$=T.readback(E.bc.buffer,E.bc.offset,4*i),L=E.arcScores===null?null:T.readback(E.arcScores.buffer,E.arcScores.offset,4*e.arcCount),F=await Vi(E,T,s?.signal);return{vertex:new Float32Array(F,$.offset,i).slice(),perArc:L===null?null:new Float32Array(F,L.offset,e.arcCount).slice(),sourcesUsed:t.length,sigmaOverflow:N,batches:C}}finally{w.dispose()}}function Zp(n,e){const t=n.nodeCount,r=n.directed?(t-1)*(t-2):(t-1)*(t-2)/2;return e===!0&&r>0?r:1}async function em(n,e){if(n.assertReady(),await Lt(n),e?.endpoints===!0)throw new S("E_UNSUPPORTED",`${wt}: endpoints: true is not supported`,{feature:"betweenness.endpoints",hint:"the CPU endpoints branch in algorithms/src/algorithms/centrality/betweenness.ts (predecessors.length === 0 && w !== source) never fires, so there is no convention to match"})}async function kN(n,e,t,r){await em(n,t);const o=e.nodeCount,s=Eo(wt,t?.dest,o)??new Float32Array(o),i=Yp(t,o);if(t?.signal?.aborted)throw sn(wt);if(o===0||i.length===0)return s.fill(0),{scores:s,iterations:0,converged:!0,precision:"f32",sourcesUsed:0,sigmaOverflow:!1};const a=await Jp(n,e,i,!1,r,t),c=(e.directed?1:2)*Zp(e,t?.normalized);for(let l=0;l<o;l++)s[l]=a.vertex[l]/c;return{scores:s,iterations:a.batches,converged:!0,precision:"f32",sourcesUsed:a.sourcesUsed,sigmaOverflow:a.sigmaOverflow}}async function SN(n,e,t,r,o){await em(n,t);const s=e.nodeCount,i=Eo("edgeBetweennessCentrality",t?.dest,e.edgeCount)??new Float32Array(e.edgeCount),a=Yp(t,s);if(t?.signal?.aborted)throw sn(wt);if(s===0||a.length===0||e.arcCount===0)return i.fill(0),{scores:i,precision:"f32",sourcesUsed:a.length,sigmaOverflow:!1};const c=await Jp(n,e,a,!0,r,t),l=c.perArc??new Float32Array(e.arcCount),u=Db(e,l,"sum"),d=(e.directed?1:2)*Zp(e,t?.normalized);for(let f=0;f<e.edgeCount;f++)i[f]=u[f]/d;return{scores:i,precision:"f32",sourcesUsed:c.sourcesUsed,sigmaOverflow:c.sigmaOverflow}}function PN(n,e,t){return kN(n,e,t,{})}function xN(n,e,t){return SN(n,e,t,{})}const Me="closenessCentrality",bs=8,CN=64,NN=4096,tm=12,TN=1024;function ko(n){return n===0?0:1/n}async function ON(n,e,t,r,o,s){const i=e.nodeCount,a=r?.length??i,c=r===null?null:new Float64Array(i);for(let l=0;l<a;l++){if(s?.signal?.aborted)throw sn(Me);const u=r===null?l:r[l],{dist:d}=await Gp(n,e,u,{signal:s?.signal});let f=0;for(let h=0;h<i;h++){const g=d[h];h!==u&&g!==1/0&&(c!==null?c[h]+=g:o?g>0&&(f+=1/g):f+=g)}c===null&&(t[u]=o?f:ko(f)),s?.onProgress?.(l+1,a)}return c?.forEach((l,u)=>{t[u]=ko(l)}),{scores:t,iterations:a,converged:!0,precision:"f32",sourcesUsed:a}}async function $N(n,e,t,r,o,s){const i=e.nodeCount,a=Mt(n,Me,Math.min(_o,Math.ceil(i/32))+3);try{const c=await Vp(n,e,a,r,_o,{signal:s?.signal},Me),l=await n.pipelines.kernel(z("closeness-rowsum")),u=kt(a.scratch(4*i,"row-sums"),4*i),d=o?2:Number(r),f=a.params(vo,{role:d,n:i}),h=new Pe(n,`${Me}/row-sums`);l.dispatch(h.pass("row-sums"),l.bind({dist:c,out:u,P:f.binding}),mo(i,n.caps),[f.offset]),h.endPass();const g=h.readback(u.buffer,u.offset,4*i);a.flush();const w=await h.submit().readback;return n.assertReady(),d===0?new Uint32Array(w,g.offset,i).forEach((p,m)=>{t[m]=ko(p)}):new Float32Array(w,g.offset,i).forEach((p,m)=>{t[m]=o?p:ko(p)}),s?.onProgress?.(i,i),{scores:t,iterations:1,converged:!0,precision:"f32",sourcesUsed:i}}finally{a.dispose()}}async function RN(n,e,t,r,o,s){const{sources:i,harmonic:a,levelsPerSubmit:c}=r,l=e.nodeCount,u=i?.length??l;if(u===0)return{scores:t,iterations:0,converged:!0,precision:"f32",sourcesUsed:0};const d=Math.min(n.caps.limits.maxStorageBufferBindingSize,n.caps.limits.maxBufferSize),f=n.residency.core(e);if(sr(f,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,Me),e.directed&&4*e.arcCount>d)throw new S("E_TOO_LARGE",`${Me}: the reverse adjacency of a directed snapshot (${4*e.arcCount} bytes) does not fit one binding`,{needed:4*e.arcCount,limit:d,path:"closeness.reverse",algorithm:Me});const h=e.directed?Ui(n.residency.view(e,"reverse"),e.arcCount):f,g=i===null?0:l,w=Math.floor((d/4-g)/(4*l)),p=i===null?bs:Math.floor(4294967295/(32*Math.max(1,l-1))),m=s.words??Math.max(1,Math.min(bs,Math.ceil(u/32),w,p));if(!Number.isInteger(m)||m<1||m>bs)throw new S("E_INVALID_ARGUMENT",`${Me}: words must be an integer in [1, ${bs}]`,{argument:"words",value:m,expected:`an integer in [1, ${bs}]`});const y=l*m,b=4*y+g;if(4*b>d)throw new S("E_TOO_LARGE",`${Me}: ${l} nodes need a ${4*b}-byte search state in one binding of at most ${d} bytes`,{needed:4*b,limit:d,path:"closeness.bits",algorithm:Me});const v=32*m,A=c*v,E=A,I=i===null?0:E+tm,k=E+tm+(i?.length??0),N=s.pullAt??Math.min(4294967295,Math.floor(m*e.arcCount/CN)),C=Mt(n,Me,c+4);try{const O=n.workgroupSize,T=kt(C.scratch(4*b,"bits"),4*b),$=kt(C.scratch(4*k,"table"),4*k),L={...$,size:4*A};i!==null&&n.device.queue.writeBuffer($.buffer,$.offset+4*I,Uint32Array.from(i)),await n.allocator.check();const F=await n.pipelines.kernel(z("closeness-level")),M=await n.pipelines.kernel(z("fill")),R={rowPtr:f.rowPtr,colIdx:f.colIdx??f.rowPtr,inRowPtr:h.rowPtr,inColIdx:h.colIdx??h.rowPtr,bits:T,table:$},D=se(Math.max(l,e.arcCount),O,n.caps),U=e.inDegree().every(q=>q<=NN)?1:0,B=i===null?null:new Float64Array(l),V={n:l,words:m,base:y,ctrl:E,pullAt:N,perNode:i===null?0:1,sourcesAt:I,arcCount:e.arcCount,pullOk:U};let W=0;for(let q=0;q<u;q+=v){const K=Math.min(v,u-q),X=new Float64Array(K),H=new Float64Array(K),Y=new Uint32Array(K);let ee=!1,Z=0;for(;!ee;){if(Z>l+1)throw new S("E_VALIDATION",`${Me}: the batch at ${q} still claimed at level ${Z}`,{label:Me,message:`the batch still claimed at level ${Z}`});const J=new Pe(n,`${Me}/levels`),ce=J.pass("closeness");if(Z===0){const ge=C.params(vo,{...V,role:1,total:b,count:K}),me=F.bind({...R,P:ge.binding});F.dispatch(ce,me,se(b,O,n.caps),[ge.offset]);const De=C.params(vo,{...V,role:2,count:K,source:q});F.dispatch(ce,me,se(K,O,n.caps),[De.offset])}const de=C.params(Ze,{count:A,value:0,mode:0,pad0:0});M.dispatch(ce,M.bind({dst:L,P:de.binding}),se(A,O,n.caps),[de.offset]);let ne=null;for(let ge=0;ge<c;ge++){const me=C.params(vo,{...V,role:0,count:K,level:Z+ge,row:ge});ne??=F.bind({...R,P:me.binding}),F.dispatch(ce,ne,D,[me.offset])}J.endPass();const ve=J.readback($.buffer,$.offset,4*A),ue=B===null?null:J.readback(T.buffer,T.offset+16*y,4*l);C.flush();const we=J.submit(),Xe=await we.readback;if(n.assertReady(),o?.signal?.aborted)throw sn(Me,we.id);const he=new Uint32Array(Xe,ve.offset,A);for(let ge=0;ge<c&&!ee;ge++){const me=Z+ge+1;let De=0;for(let Ne=0;Ne<K;Ne++){const He=he[ge*v+Ne];X[Ne]+=He*me,H[Ne]+=He/me,Y[Ne]+=He,De+=He}ee=De===0}ee&&B!==null&&ue!==null&&new Uint32Array(Xe,ue.offset,l).forEach((ge,me)=>{B[me]+=ge}),Z+=c}if(i===null){for(let J=0;J<K;J++)t[q+J]=a?H[J]:ko(X[J]);s.onBatch?.(q,X,Y)}W+=1,o?.onProgress?.(q+K,u)}return B?.forEach((q,K)=>{t[K]=ko(q)}),{scores:t,iterations:W,converged:!0,precision:"f32",sourcesUsed:u}}finally{C.dispose()}}function DN(n,e){if(e===void 0)return null;if(n.directed)throw new S("E_UNSUPPORTED",`${Me}: sampled sources need an undirected snapshot`,{feature:"closenessCentrality.directedSources",hint:"run the CPU port, which searches the in-arcs"});for(const t of e)if(!Number.isInteger(t)||t<0||t>=n.nodeCount)throw new S("E_INVALID_ARGUMENT",`${Me}: a source is not a node index`,{argument:"sources",value:t,expected:`an integer in [0, ${n.nodeCount})`});return e}async function LN(n,e,t,r){n.assertReady(),await Lt(n);for(const f of["maxIterations","tolerance"])if(t?.[f]!==void 0)throw new S("E_UNSUPPORTED",`${Me}: ${f} has no meaning for an exact traversal`,{option:f,hint:"closeness is an exact traversal; the option has no meaning here"});const o=e.nodeCount,s=DN(e,t?.sources),i=t?.harmonic===!0;if(i&&s!==null)throw new S("E_UNSUPPORTED",`${Me}: harmonic closeness from sampled sources`,{feature:"closenessCentrality.sampledHarmonic",hint:"run the CPU port, or drop the sources for the exact harmonic score"});const a=r.levelsPerSubmit??$e;if(!Number.isInteger(a)||a<1||a>$e)throw new S("E_INVALID_ARGUMENT",`${Me}: levelsPerSubmit must be an integer in [1, ${$e}]`,{argument:"levelsPerSubmit",value:a,expected:`an integer in [1, ${$e}]`});const c=Eo(Me,t?.dest,o)??new Float32Array(o),l=(t?.weighted??e.flags.weighted)&&e.weights!==null&&!e.flags.allWeightsOne;if(t?.signal?.aborted)throw sn(Me);if(l&&!e.flags.nonNegativeWeights)throw new S("E_UNSUPPORTED",`${Me}: a negative weight has no shortest-path distance to sum`,{feature:"closenessCentrality.negativeWeights",hint:"pass weighted: false to ignore the column"});if(l&&!e.flags.finiteWeights)throw new S("E_UNSUPPORTED",`${Me}: a NaN or infinite weight has no shortest path`,{feature:"closenessCentrality.nonFiniteWeights"});const u=o>0&&o<=Wp(n.caps.limits).maxNodes;let d;return s!==null||!u?d=l?"per-source":"levels":d=r.route??(l||o<=TN?"all-pairs":"levels"),d==="levels"&&l&&(d="per-source"),r.onRoute?.(d),d==="all-pairs"?$N(n,e,c,l,i,t):d==="per-source"?ON(n,e,c,s,i,t):RN(n,e,c,{sources:s,harmonic:i,levelsPerSubmit:a},t,r)}function MN(n,e,t){return LN(n,e,t,{})}const Ut="connectedComponents",Ol=4,$l=64,UN=1024,FN=1024,BN=2*Ol;function zN(n,e){if(n===void 0)return null;if(n instanceof Uint32Array&&n.length===e&&n.buffer instanceof ArrayBuffer)return n;throw new S("E_INVALID_ARGUMENT",`${Ut}: dest must be a Uint32Array of length ${e} over an ArrayBuffer`,{argument:"dest",value:`${n.constructor.name}(${n.length})`,expected:`Uint32Array(${e}) over an ArrayBuffer`})}function GN(n,e){const t=n.residency.core(e);return sr(t,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,Ut),t}function Rl(n,e){return{buffer:n,offset:0,size:e,window:null}}function So(n,e){let t=null;return{labels:n,count:e,groups(){if(t!==null)return t;const r=n.length,o=new Uint32Array(r).fill(Ve),s=new Uint32Array(e);let i=0;for(let l=0;l<r;l++){let u=o[n[l]];u===Ve&&(u=i++,o[n[l]]=u),s[u]++}const a=Array.from(s,l=>new Uint32Array(l)),c=new Uint32Array(e);for(let l=0;l<r;l++){const u=o[n[l]];a[u][c[u]++]=l}return t=a,a}}}function WN(n){const e=new Map;let t=n[0],r=0;for(const o of n){const s=(e.get(o)??0)+1;e.set(o,s),s>r&&(t=o,r=s)}return t}function VN(n){const e=n.length,t=new Uint8Array(e);let r=0;for(let o=0;o<e;o++){const s=n[o];if(s>=e)throw new S("E_VALIDATION",`${Ut}: labels[${o}] = ${s} is not a node index`,{label:`${Ut}/labels`,message:`the device produced a label outside [0, ${e})`});t[s]===0&&(t[s]=1,r++)}return r}function jN(n,e,t){const r=e??new Uint32Array(n);for(let o=0;o<n;o++)r[o]=o;return t?.onProgress?.(1,1),So(r,n)}function qN(n,e,t,r,o){if(o?.aborted)throw new S("E_ABORTED",`${Ut}: the signal was aborted`,{batchId:r});if(new Uint32Array(n,e,1)[0]===0)return!0;if(t>=$l)throw new S("E_VALIDATION",`${Ut}: the changed flag never settled in ${$l} rounds`,{label:Ut,message:`the changed flag never settled in ${$l} rounds`});return!1}async function nm(n,e,t){n.assertReady(),await Lt(n);const r=e.nodeCount,o=t?.renumber!==!1,s=zN(t?.dest,r);if(t?.signal?.aborted)throw new S("E_ABORTED",`${Ut}: the signal was aborted before any work started`,{});if(r===0)return t?.onProgress?.(1,1),So(s??new Uint32Array(0),0);const i=GN(n,e);if(e.arcCount===0)return jN(r,s,t);const a=n.residency.view(e,"edgeList"),c=a.scalars.edgeCount[0],l=Mt(n,Ut,BN);try{const u=4*(r+1),d=l.scratch(u,"comp"),f=Math.min(UN,r),h=l.scratch(4*f,"hist");await n.allocator.check();const g=await n.pipelines.kernel(z("fill",{})),w=await n.pipelines.kernel(z("wcc-link-sample",Ct(i,null))),p=await n.pipelines.kernel(z("wcc-link-edges",{})),m=await n.pipelines.kernel(z("wcc-compress",{})),y=await n.pipelines.kernel(z("wcc-sample",{})),{queue:b}=n.device,v=Rl(d,u),A=Rl(h,4*f),E=gt(r,n.workgroupSize,n.caps),I=gt(c,n.workgroupSize,n.caps),k=r,N=new Uint32Array(1),C=Z=>l.params(bo,{n:r,...Z,flagIndex:k,maxSteps:FN,pad0:0}),O=Z=>{const J=C({items:r,stride:E.stride??r,r:0,giant:Ve});m.dispatch(Z,m.bind({comp:v,P:J.binding}),E,[J.offset])},T=Z=>(l.flush(),Z.submit());b.writeBuffer(d,4*k,N);const $=new Pe(n,`${Ut}/setup`);let L=$.pass("sample-rounds");const F=l.params(Ze,{count:r,value:0,mode:1,pad0:0});g.dispatch(L,g.bind({dst:Rl(d,4*r),P:F.binding}),se(r,n.workgroupSize,n.caps),[F.offset]);const M=on(i,null);for(let Z=0;Z<2;Z++){const J=C({items:r,stride:E.stride??r,r:Z,giant:Ve}),ce=w.bind({...M,comp:v,P:J.binding});w.dispatch(L,ce,E,[J.offset])}O(L),$.endPass(),await T($).readback,n.assertReady();const R=new Pe(n,`${Ut}/sample`);L=R.pass("sample");const D=C({items:f,stride:0,r:0,giant:Ve});y.dispatch(L,y.bind({comp:v,hist:A,P:D.binding}),se(f,n.workgroupSize,n.caps),[D.offset]),R.endPass();const U=R.readback(h,0,4*f),B=await T(R).readback;n.assertReady();const V=WN(new Uint32Array(B,U.offset,f)),W={edgeSrc:a.bindings.src,edgeDst:a.bindings.dst,comp:v};let q=0;for(;;){b.writeBuffer(d,4*k,N);const Z=new Pe(n,`${Ut}/rounds`);L=Z.pass("edge-rounds");for(let ne=0;ne<Ol;ne++){const ve=C({items:c,stride:I.stride??c,r:0,giant:V}),ue=p.bind({...W,P:ve.binding});p.dispatch(L,ue,I,[ve.offset]),O(L)}Z.endPass();const J=Z.readback(d,4*k,4),ce=T(Z),de=await ce.readback;if(q+=Ol,n.assertReady(),qN(de,J.offset,q,ce.id,t?.signal))break}const K=new Pe(n,`${Ut}/final`);O(K.pass("compress")),K.endPass(),await T(K).readback,n.assertReady();const X=!o&&s!==null?s:new Uint32Array(r);await n.readback.read(d,4*r,X),n.assertReady();const H=VN(X);if(t?.onProgress?.(1,1),!o)return So(X,H);const{labels:Y,count:ee}=Je(X,s??void 0);return So(Y,ee)}finally{l.dispose()}}function HN(n,e=jk){if(!Number.isInteger(e)||e<0||e>al)throw new S("E_INVALID_ARGUMENT",`planGroupRows: threadMax must be an integer in [0, ${al}]`,{argument:"threadMax",value:e,expected:`[0, ${al}]`});const t=n.length,r=[],o=[];for(let a=0;a<t;a++)(n[a]<=e?r:o).push(a);const s=new Uint32Array(r.length+2*o.length);s.set(r,0),s.set(o,r.length);let i=1;for(let a=0;a<o.length;a++)s[r.length+o.length+a]=i,i+=2*Fw*n[o[a]];return{words:s,threadCount:r.length,hashCount:o.length,regionWords:i}}async function KN(n){const e=new Map;for(const t of[0,1])for(const r of[!1,!0]){const o=z("group-by-key-row",{TIER:t,WEIGHTED:r});e.set(`${t}/${r}`,await n.pipelines.kernel(o))}return new YN(n,e)}function Dl(n,e,t){if(e.size<4*t)throw new S("E_INVALID_ARGUMENT",`groupByKeyRow: ${n} is smaller than 4 x ${t} bytes`,{argument:n,value:e.size,expected:4*t})}class YN{constructor(e,t){this.scope=e,this.kernels=t}record(e,t){const{threadCount:r,hashCount:o}=t.plan,s=r+o;if(Dl("rows",t.rows,s+o),Dl("hashRegion",t.hashRegion,t.plan.regionWords),Dl("rowPtr",t.rowPtr,s+1),s===0)return;const i=t.weights!==null,a=[[0,0,r],[1,r,o]];for(const[c,l,u]of a){if(u===0)continue;const d=this.kernels.get(`${c}/${i}`);if(d===void 0)throw new S("E_INVALID_ARGUMENT","groupByKeyRow: no variant was prepared",{argument:"tier",value:c});const f=this.scope.params(bp,{rowsBase:l,basesBase:r+o,count:u,pad0:0}),h=d.bind({rowPtr:t.rowPtr,colIdx:t.colIdx,weights:t.weights??t.colIdx,keyIn:t.keyIn,rows:t.rows,hashRegion:t.hashRegion,bestKey:t.bestKey,bestScore:t.bestScore,P:f.binding}),g=c===0?se(u,this.scope.workgroupSize,this.scope.caps):mo(u,this.scope.caps);d.dispatch(e,h,g,[f.offset])}}}const rm=4294967295;async function om(n){return sm(n)}async function sm(n){const e=await n.pipelines.kernel(z("histogram")),t=await n.pipelines.kernel(z("fill"));return new QN(n,e,t)}async function XN(n){const e=await sm(n),t=await Or(n),r=await n.pipelines.kernel(z("counting-scatter"));return new JN(n,e,t,r)}function vs(n,e,t){if(e.size<4*t)throw new S("E_INVALID_ARGUMENT",`histogram: ${n} is smaller than 4 x ${t} bytes`,{argument:n,value:e.size,expected:4*t})}function im(n,e,t,r){if(!Number.isSafeInteger(e)||e<0||e>rm)throw new S("E_INVALID_ARGUMENT","histogram: count must be a non-negative integer below 2^32",{argument:"count",value:e});if(!Number.isSafeInteger(t)||t<1||t>rm)throw new S("E_INVALID_ARGUMENT","histogram: bins must be an integer in [1, 2^32)",{argument:"bins",value:t});vs("keys",n,e),vs("hist",r,t)}class QN{constructor(e,t,r){this.dispatches=0,this.scope=e,this.histogram=t,this.fill=r}get lastDispatches(){return this.dispatches}record(e,t,r,o,s){if(im(t,r,o,s),this.recordZero(e,s,o),this.dispatches=1,r===0)return;const i=this.scope.params($i,{count:r,bins:o,pad0:0,pad1:0}),a=this.histogram.bind({keys:t,hist:s,P:i.binding});this.histogram.dispatch(e,a,se(r,this.scope.workgroupSize,this.scope.caps),[i.offset]),this.dispatches=2}recordZero(e,t,r){const o=this.scope.params(Ze,{count:r,value:0,mode:0,pad0:0}),s=this.fill.bind({dst:t,P:o.binding});this.fill.dispatch(e,s,se(r,this.scope.workgroupSize,this.scope.caps),[o.offset])}}class JN{constructor(e,t,r,o){this.dispatches=0,this.scope=e,this.histogram=t,this.scan=r,this.scatter=o}get lastDispatches(){return this.dispatches}record(e,t,r,o,s,i,a){if(im(t,r,o,s.hist),vs("cursor",s.cursor,o),vs("outIndex",i,r),vs("outStart",a,o),this.histogram.record(e,t,r,o,s.hist),this.scan.record(e,s.hist,o,a),this.histogram.recordZero(e,s.cursor,o),this.dispatches=this.histogram.lastDispatches+this.scan.lastDispatches+1,r===0)return;const c=this.scope.params($i,{count:r,bins:o,pad0:0,pad1:0}),l=this.scatter.bind({keys:t,start:a,cursor:s.cursor,outIndex:i,P:c.binding});this.scatter.dispatch(e,l,se(r,this.scope.workgroupSize,this.scope.caps),[c.offset]),this.dispatches+=1}}async function am(n){const e=await om(n),t=await Or(n),r=await n.pipelines.kernel(z("fill")),o=new Map;for(const s of[!1,!0])for(const i of[!1,!0]){const a=z("coo-scatter",{SORTED_INPUT:s,WEIGHTED:i});o.set(`${s}/${i}`,await n.pipelines.kernel(a))}return new eT(n,e,t,r,o)}function $r(n,e,t){if(e.size<4*t)throw new S("E_INVALID_ARGUMENT",`cooToCsr: ${n} is smaller than 4 x ${t} bytes`,{argument:n,value:e.size,expected:4*t})}function ZN(n){for(const[e,t]of[["count",n.count],["n",n.n]])if(!Number.isSafeInteger(t)||t<0||t>=Ve)throw new S("E_INVALID_ARGUMENT",`cooToCsr: ${e} must be an integer in [0, 2^32 - 1)`,{argument:e,value:t});if(n.weights===null!=(n.out.weights===null))throw new S("E_INVALID_ARGUMENT","cooToCsr: weights and out.weights must be both present or both null",{argument:"weights",value:n.weights===null?"null":"present",expected:n.out.weights===null?"null":"present"});$r("src",n.src,n.count),$r("dst",n.dst,n.count),$r("out.rowPtr",n.out.rowPtr,n.n+1),$r("out.colIdx",n.out.colIdx,n.count),$r("out.flag",n.out.flag,1),n.weights!==null&&n.out.weights!==null&&($r("weights",n.weights,n.count),$r("out.weights",n.out.weights,n.count))}class eT{constructor(e,t,r,o,s){this.scope=e,this.histogram=t,this.scan=r,this.fill=o,this.scatter=s}record(e,t){ZN(t);const{scope:r}=this,o=r.workgroupSize,s=4*(t.n+1),i={buffer:r.scratch(s,"cooToCsr/degrees"),offset:0,size:s,window:null};this.histogram.record(e,t.src,t.count,t.n+1,i),this.scan.record(e,i,t.n+1,t.out.rowPtr);let a=t.out.flag;if(t.sortedInput)this.zero(e,t.out.flag,1);else if(t.n>0){const h=4*t.n;a={buffer:r.scratch(h,"cooToCsr/cursors"),offset:0,size:h,window:null},this.zero(e,a,t.n)}if(t.count===0)return;const c=t.weights!==null,l=this.scatter.get(`${t.sortedInput}/${c}`);if(l===void 0)throw new S("E_INVALID_ARGUMENT","cooToCsr: no scatter variant was prepared",{argument:"sortedInput",value:t.sortedInput});const u=t.out.weights??{buffer:r.scratch(4,"cooToCsr/weight-dummy"),offset:0,size:4,window:null},d=r.params(vn,{count:t.count,pad0:0,pad1:0,pad2:0}),f=l.bind({src:t.src,dst:t.dst,weight:t.weights??t.dst,rowPtr:t.out.rowPtr,cursors:a,colIdx:t.out.colIdx,outWeight:u,P:d.binding});l.dispatch(e,f,se(t.count,o,r.caps),[d.offset])}zero(e,t,r){const o=this.scope.params(Ze,{count:r,value:0,mode:0,pad0:0}),s=this.fill.bind({dst:t,P:o.binding});this.fill.dispatch(e,s,se(r,this.scope.workgroupSize,this.scope.caps),[o.offset])}}const cm=2**128-2**104;function tT(n){let e=0;n==="min"?e=cm:n==="max"&&(e=-cm);const t=new DataView(new ArrayBuffer(4));return t.setFloat32(0,e,!0),t.getUint32(0,!0)}const nT=new Set(["row","arc","nbr","weight","v"]),rT=new Set(["if","else","let","var","const","true","false","f32","u32","i32","bool","abs","ceil","clamp","exp","exp2","floor","fract","inverseSqrt","log","log2","max","min","mix","pow","round","select","sign","sqrt","step","trunc"]);function oT(n){switch(n){case"sum":return 0;case"min":return 1;case"max":return 2;default:throw new S("E_INVALID_ARGUMENT",`segmentedReduce: unknown op ${String(n)}`,{argument:"op",value:n,expected:"sum | min | max"})}}function sT(n){return n.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g," ")}function iT(n){const e=sT(n);if(!/\bv\s*[-+*/]?=(?!=)/.test(e))throw new S("E_SHADER_COMPILE","segmentedReduce: the VALUE snippet never assigns v",{id:"segmented-reduce",stage:"compose",slot:"VALUE"});const t=e.match(/[A-Za-z_]\w*|\d[0-9A-Za-z_.]*/g)??[];for(const r of t)if(!(/^\d/.test(r)||nT.has(r)||rT.has(r)))throw new S("E_SHADER_COMPILE",`segmentedReduce: the VALUE snippet names "${r}"; the only identifiers allowed are row, arc, nbr, weight and v`,{id:"segmented-reduce",stage:"compose",slot:"VALUE",identifier:r})}function aT(n,e,t,r,o,s){return r!==null&&s?{first:r.rowFirst,last:r.rowLast+1,arcEnd:r.end}:{first:n.start,last:n.tier===0?t:n.end,arcEnd:r===null?Li(e):Math.min(r.end,o)}}function cT(n,e){return n===2?1:n===1?e/Mn:e}class lT{constructor(e,t,r,o,s,i,a){this.dispatches=0,this.scope=e,this.tiers=t,this.fill=r,this.perm=o,this.hasWeights=s,this.accumulate=i,this.identityWord=a}get lastDispatches(){return this.dispatches}record(e,t,r){if(t.weights!==null!==this.hasWeights)throw new S("E_INVALID_ARGUMENT","segmentedReduce: the core's weights pattern differs from the one prepared",{argument:"core",value:t.weights!==null,expected:this.hasWeights});const o=ps(t,"segmentedReduce");if(r.size<4*o)throw new S("E_INVALID_ARGUMENT",`segmentedReduce: out holds ${r.size} bytes, ${4*o} needed`,{argument:"out",value:r.size,expected:`>= ${4*o}`});if(this.dispatches=0,o===0)return;if(t.windows===null){this.recordWindow(e,t,r,o,null,0);return}if(!this.accumulate){const i=this.scope.params(Ze,{count:o,value:this.identityWord,mode:0}),a=this.fill.bind({dst:r,P:i.binding});this.fill.dispatch(e,a,se(o,this.scope.workgroupSize,this.scope.caps),[i.offset]),this.dispatches++}const{windows:s}=t;s.forEach((i,a)=>{const c={...t,colIdx:Mi(t,"colIdx",i),weights:t.weights===null?null:Mi(t,"weights",i)};this.recordWindow(e,c,r,o,i,a+1<s.length?s[a+1].start:i.end)})}recordWindow(e,t,r,o,s,i){const a=this.scope.workgroupSize;for(const c of this.tiers){const{tier:l,kernel:u}=c,{first:d,last:f,arcEnd:h}=aT(c,t,o,s,i,this.perm===null),g=f-d;if(g<=0)continue;const w=this.scope.params(vl,{start:d,end:f,arcBase:s===null?0:s.start,arcEnd:h,accumulate:s!==null||this.accumulate?1:0,n:o}),p=u.bind({...on(t,this.perm),out:r,P:w.binding});u.dispatch(e,p,se(g,cT(l,a),this.scope.caps),[w.offset]),this.dispatches++}}}async function lm(n,e,t){const r=oT(t.op);iT(t.valueSnippet);const{tiers:o}=t,s=o?.perm??null;if(o!==null&&n.workgroupSize<Mn)throw new S("E_UNSUPPORTED",`segmentedReduce: the mid tier folds ${Mn} lanes per row, more than the workgroup size ${n.workgroupSize}`,{feature:"segmentedReduce.tiers"});const i=o===null?[{tier:0,start:0,end:ps(e,"segmentedReduce")}]:[{tier:2,start:0,end:o.segmentOffsets[1]},{tier:1,start:o.segmentOffsets[1],end:o.segmentOffsets[2]},{tier:0,start:o.segmentOffsets[2],end:o.segmentOffsets[4]}],a=[];for(const l of i){if(l.tier!==0&&l.end<=l.start)continue;const u={...Ct(e,s),OP:r,TIER:l.tier},d=z("segmented-reduce",u,{VALUE:t.valueSnippet});a.push({...l,kernel:await n.pipelines.kernel(d)})}const c=await n.pipelines.kernel(z("fill"));return new lT(n,a,c,s,e.weights!==null,t.accumulate===!0,tT(t.op))}function uT(n){for(const e of[8,16,24])if(n<2**e)return e;return 32}function qe(n,e,t){const r=4*Math.max(1,e);return{buffer:n.scratch(r,t),offset:0,size:r,window:null}}function um(n,e,t,r){const o=n.caps.limits.maxStorageBufferBindingSize;if(e>o)throw new S("E_TOO_LARGE",`${r}: ${t} needs ${e} bytes in one binding, above the device limit of ${o}`,{needed:e,limit:o,path:t,algorithm:r})}function dT(n,e,t,r){const o=new Uint32Array(n);for(let a=0;a<e.length;a++)e[a]!==t[a]&&(o[e[a]]++,o[t[a]]++);const s=new Map;for(let a=0;a<n;a++)o[a]>cl&&s.set(a,s.size);if(s.size<2)return;const i=new Uint32Array(s.size*s.size);for(let a=0;a<e.length;a++){const c=s.get(e[a]),l=s.get(t[a]);if(c===void 0||l===void 0||c===l)continue;const u=Math.min(c,l)*s.size+Math.max(c,l);if(++i[u]>cl)throw new S("E_UNSUPPORTED",`${r}: nodes ${e[a]} and ${t[a]} are joined by more than ${cl} parallel edges, more than one weighted merge sums`,{feature:`${r}.parallelEdges`,hint:"run it unweighted, or merge the parallel edges first"})}}function Ll(n,e,t){if(new Uint32Array(n,e.flag.offset,1)[0]!==0)throw new S("E_VALIDATION",`${t}: the simple graph's arcs reached cooToCsr out of order`,{label:`${t}/simple-graph`,message:"the sorted-input precondition of cooToCsr failed on the device"})}async function dm(n,e,t,r,o){const s=e.nodeCount,i=n.workgroupSize,a=await am(t),c=qe(t,1,"simple/flag"),l=qe(t,s+1,"simple/rowPtr"),{edgeCount:u}=e,d=e.edgeList();let f=0;for(let Ae=0;Ae<u;Ae++)d.src[Ae]===d.dst[Ae]&&f++;const h=2*(u-f),g=()=>{const Ae=new Pe(n,`${o}/simple-graph`);return a.record(Ae.pass("simple-graph"),{src:c,dst:c,weights:null,count:0,n:s,sortedInput:!0,out:{rowPtr:l,colIdx:c,weights:null,flag:c}}),Ae.endPass(),{graph:{n:s,arcCount:0,rowPtr:l,colIdx:null,weights:null,src:null},batch:Ae,flag:Ae.readback(c.buffer,0,4)}};if(h===0)return g();const w=2*u,p=Math.max(4,zi(w,i));um(n,Math.max(4*(w+1),p),"the simple graph's arc arrays",o),r&&dT(s,d.src,d.dst,o),n.residency.core(e,["rowPtr"]);const m=n.residency.view(e,"edgeList"),y=m.bindings.weights??null,b=se(w,i,n.caps),v=new Map;for(const Ae of[!1,!0]){const yt=z("coo-emit",{INDEXED:Ae,WEIGHTED:y!==null});v.set(Ae,await n.pipelines.kernel(yt))}const A=await n.pipelines.kernel(z("fill")),E=await n.pipelines.kernel(z("run-flags")),I=await Sl(t),k=await Or(t),N=await Bi(t),C=qe(t,w,"simple/aSrc"),O=qe(t,w,"simple/aDst"),T=qe(t,w,"simple/aW"),$=qe(t,w,"simple/vals"),L=qe(t,w,"simple/sortKeys"),F=qe(t,w,"simple/sortVals"),M={buffer:t.scratch(p,"simple/hist"),offset:0,size:p,window:null},R={buffer:t.scratch(p,"simple/offsets"),offset:0,size:p,window:null},D=qe(t,w,"simple/sortedSrc"),U=qe(t,w,"simple/sortedDst"),B=qe(t,w,"simple/sortedW"),V=qe(t,w,"simple/flags"),W=qe(t,w,"simple/runIndex"),q=qe(t,1,"simple/dummy");await n.allocator.check();const K=(Ae,yt,Bn)=>{const ur=v.get(yt!==null);if(ur===void 0)throw new S("E_INVALID_ARGUMENT","buildSimpleSymmetric: no coo-emit variant",{argument:"order",value:yt===null?"null":"present"});const ra=t.params(vn,{count:w,pad0:0,pad1:0,pad2:0}),gu=ur.bind({edgeSrc:m.bindings.src,edgeDst:m.bindings.dst,edgeWeight:y??m.bindings.src,order:yt??q,outSrc:Bn[0],outDst:Bn[1],outWeight:Bn[2],P:ra.binding});ur.dispatch(Ae,gu,b,[ra.offset])},X=(Ae,yt,Bn)=>{const ur=t.params(Ze,{count:Bn,value:0,mode:1,pad0:0});A.dispatch(Ae,A.bind({dst:yt,P:ur.binding}),se(Bn,i,n.caps),[ur.offset])},H=uT(s),Y=new Pe(n,`${o}/simple-sort`),ee=Y.pass("simple-sort");K(ee,null,[C,O,T]),X(ee,$,w);const Z=I.record(ee,O,$,w,H,{keys:L,vals:F,hist:M,offsets:R});K(ee,Z.vals,[C,O,T]);const J=Z.vals.buffer===$.buffer?F:$,ce=I.record(ee,C,Z.vals,w,H,{keys:Z.keys.buffer===O.buffer?L:O,vals:J,hist:M,offsets:R});K(ee,ce.vals,[D,U,B]);const de=t.params(vn,{count:w,pad0:0,pad1:0,pad2:0});E.dispatch(ee,E.bind({keysA:D,keysB:U,flags:V,P:de.binding}),b,[de.offset]);const ne=k.record(ee,V,w,W);Y.endPass();const ve=Y.readback(ne.binding.buffer,ne.binding.offset+4*ne.index,4);t.flush();const ue=await Y.submit().readback;n.assertReady();const we=new Uint32Array(ue,ve.offset,1)[0];if(we===0||we>h)throw new S("E_VALIDATION",`${o}: ${we} distinct arcs from ${h} valid ones`,{label:`${o}/simple-graph`,message:"the run count of the simple graph build is outside [1, valid arcs]"});const Xe=qe(t,w,"simple/src"),he=qe(t,w,"simple/dst"),ge=qe(t,w+1,"simple/runStart"),me=qe(t,1,"simple/count"),De=qe(t,we,"simple/colIdx"),Ne=r?qe(t,we,"simple/weights"):null,He=r?qe(t,we,"simple/merged"):null;n.device.queue.writeBuffer(ge.buffer,4*we,Uint32Array.of(h));const _n=He===null?null:await lm(t,fm(ge,we,U,B,h),{op:"sum",valueSnippet:"v = weight;",tiers:null}),mt=new Pe(n,`${o}/simple-graph`),Ft=mt.pass("simple-graph"),Nt=$;X(Ft,Nt,w);for(const[Ae,yt]of[[D,Xe],[U,he],[Nt,ge]])N.record(Ft,{queue:Ae,flags:V,count:w,out:yt,outCount:me,outIndex:0});return _n!==null&&He!==null&&_n.record(Ft,fm(ge,we,U,B,h),He),a.record(Ft,{src:Xe,dst:he,weights:He,count:we,n:s,sortedInput:!0,out:{rowPtr:l,colIdx:De,weights:Ne,flag:c}}),mt.endPass(),{graph:{n:s,arcCount:we,rowPtr:l,colIdx:De,weights:Ne,src:Xe},batch:mt,flag:mt.readback(c.buffer,0,4)}}function fm(n,e,t,r,o){return{serial:-1,plan:"perArray",rowPtr:{...n,size:4*(e+1)},colIdx:{...t,size:4*o},weights:{...r,size:4*o},arcToEdge:null,edgeToArc:null,windows:null,arcBuffers:null,hasWeights:!0}}const pt="labelPropagation",fT=100,hT=1024,Ml=857579651;function gT(n){return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,n>>>0}function wT(n){return n^=n>>>16,n=Math.imul(n,2127672349),n^=n>>>13^n>>>26,n=Math.imul(n,2781581891),n^=n>>>16,n>>>0}function pT(n,e){if(n===void 0)return null;if(n instanceof Uint32Array&&n.length===e&&n.buffer instanceof ArrayBuffer)return n;throw new S("E_INVALID_ARGUMENT",`${pt}: dest must be a Uint32Array of length ${e} over an ArrayBuffer`,{argument:"dest",value:`${n.constructor.name}(${n.length})`,expected:`Uint32Array(${e}) over an ArrayBuffer`})}function mT(n){if(n===void 0)return fT;if(!Number.isSafeInteger(n)||n<0)throw new S("E_INVALID_ARGUMENT",`${pt}: maxIterations must be a non-negative integer`,{argument:"maxIterations",value:n,expected:"a non-negative integer"});return n}function yT(n){const e=n.outDegree();if(!n.directed)return e;const t=n.inDegree(),r=new Uint32Array(n.nodeCount);for(let o=0;o<r.length;o++)r[o]=e[o]+t[o];return r}function bT(n,e){const t=n.length;for(let s=0;s<t;s++){const i=wT(n[s]);if(i>=t)throw new S("E_VALIDATION",`${pt}: labels[${s}] = ${n[s]} is not a node's label`,{label:`${pt}/labels`,message:`the device produced a label that scrambles no index in [0, ${t})`});n[s]=i}const{labels:r,count:o}=Je(n,e??void 0);return So(r,o)}function hm(n,e){const t=e??new Uint32Array(n);for(let r=0;r<n;r++)t[r]=r;return So(t,n)}async function vT(n,e,t){n.assertReady(),await Lt(n);const r=e.nodeCount,o=pT(t?.dest,r),s=mT(t?.maxIterations),i=t?.weighted!==!1;if(t?.signal?.aborted)throw new S("E_ABORTED",`${pt}: the signal was aborted before any work started`,{});if(r===0||e.edgeCount===0||s===0)return t?.onProgress?.(1,1),hm(r,o);if(r>Ml)throw new S("E_TOO_LARGE",`${pt}: ${r} nodes, above the ${Ml} the labels allow`,{needed:r,limit:Ml,path:"the scrambled labels",algorithm:pt});const a=HN(yT(e));um(n,4*a.regionWords,"the group-by hash region",pt);const c=Mt(n,pt,hT);try{const l=await dm(n,e,c,i,pt),{graph:u}=l;if(u.colIdx===null){c.flush();const M=await l.batch.submit().readback;return n.assertReady(),Ll(M,l,pt),t?.onProgress?.(1,1),hm(r,o)}const d=n.workgroupSize,f=(M,R)=>{const D=4*Math.max(1,M);return{buffer:c.scratch(D,R),offset:0,size:D,window:null}},h=f(a.words.length,"rows"),g=f(a.regionWords,"hashRegion"),w=f(r,"labelsA"),p=f(r,"labelsB"),m=f(r,"bestKey"),y=f(r,"bestScore"),b=f(Uw,"counters");await n.allocator.check();const{queue:v}=n.device;v.writeBuffer(h.buffer,0,a.words),v.writeBuffer(g.buffer,0,new Uint32Array(1));const A=await KN(c),E=await n.pipelines.kernel(z("lpa-step")),I=se(r,d,n.caps),k=new Uint32Array(r);for(let M=0;M<r;M++)k[M]=gT(M);v.writeBuffer(w.buffer,0,k);let{batch:N}=l,C=!0,O=w,T=p,$=0,L=-1;for(;;){const M=Math.min(Uw,s-$);v.writeBuffer(b.buffer,0,new Uint32Array(M));const R=N.pass("passes");for(let K=0;K<M;K++){A.record(R,{rowPtr:u.rowPtr,colIdx:u.colIdx,weights:i?u.weights:null,keyIn:O,plan:a,rows:h,hashRegion:g,bestKey:m,bestScore:y});const X=c.params(vp,{n:r,direction:($+K+1)%2,counterIndex:K,pad0:0});E.dispatch(R,E.bind({labelsIn:O,bestKey:m,labelsOut:T,counters:b,P:X.binding}),I,[X.offset]),[O,T]=[T,O]}N.endPass();const D=N.readback(b.buffer,0,4*M),U=N.readback(g.buffer,0,4);c.flush();const B=N.submit(),V=await B.readback;if(n.assertReady(),C&&(Ll(V,l,pt),C=!1),new Uint32Array(V,U.offset,1)[0]!==0)throw new S("E_VALIDATION",`${pt}: a hash probe exhausted its bound`,{label:`${pt}/group-by-key`,message:"a compare-exchange loop of the workgroup tier ran out of steps"});const W=new Uint32Array(V,D.offset,M);$+=M;const q=M>=2?W[M-2]+W[M-1]:L+W[0];if(L=W[M-1],t?.signal?.aborted)throw new S("E_ABORTED",`${pt}: the signal was aborted`,{batchId:B.id});if(t?.onProgress?.($,s),q===0||$>=s)break;N=new Pe(n,`${pt}/passes`)}const F=new Uint32Array(r);return await n.readback.read(O.buffer,4*r,F),n.assertReady(),bT(F,o)}finally{c.dispose()}}const an="minimumSpanningTree",Ul=1024,AT=64,ET=5+Nr;function _T(n){let e=1;for(let t=Ul;t<n;t*=Ul)e++;return e}function IT(n,e,t){const r=new Uint32Array(t),{weights:o}=n.edgeList();let s=0,i=0;for(const a of e)if(a!==x){if(a>=n.edgeCount||s===t)throw new S("E_VALIDATION",`${an}: the device recorded an edge it did not count`,{label:`${an}/treeEdge`,message:`edge ${a} at forest position ${s} of ${t}`});r[s++]=a,i+=o===null?1:o[a]}if(s!==t)throw new S("E_VALIDATION",`${an}: ${s} recorded edges, ${t} counted`,{label:`${an}/treeEdge`,message:"the per-round counts disagree with the recorded forest"});return{edges:r,totalWeight:i}}async function kT(n,e,t){n.assertReady(),await Lt(n);const r=e.nodeCount,o=e.edgeCount;if(r===0||o===0)return{edges:new Uint32Array(0),totalWeight:0};n.residency.core(e,["rowPtr"]);const s=n.residency.view(e,"edgeList"),i=s.bindings.weights??null,a=Mt(n,an,ET);try{const c=n.workgroupSize,l=(F,M)=>{const R=4*Math.max(1,F);return{buffer:a.scratch(R,M),offset:0,size:R,window:null}},u=l(r,"comp"),d=l(r,"bestKey"),f=l(r,"bestEdge"),h=l(r,"treeEdge"),g=l(Nr,"counters");await n.allocator.check();const w=await n.pipelines.kernel(z("fill")),p=i!==null,m=await n.pipelines.kernel(z("mst-best",{PASS:0,WEIGHTED:p})),y=await n.pipelines.kernel(z("mst-best",{PASS:1,WEIGHTED:p})),b=await n.pipelines.kernel(z("mst-link")),v=await n.pipelines.kernel(z("wcc-compress")),A=se(r,c,n.caps),E=se(o,c,n.caps),I=gt(r,c,n.caps),k=_T(r),{queue:N}=n.device;let C=new Pe(n,`${an}/rounds`),O=!0,T=0,$=0;for(;;){N.writeBuffer(g.buffer,0,new Uint32Array(Nr));const F=C.pass("rounds"),M=(H,Y)=>a.params(Ze,{count:r,value:H,mode:Y,pad0:0});if(O){const H=M(0,1);w.dispatch(F,w.bind({dst:u,P:H.binding}),A,[H.offset]);const Y=M(x,0);w.dispatch(F,w.bind({dst:h,P:Y.binding}),A,[Y.offset])}const R=M(Ve,0),D=a.params(Di,{count:o,counterIndex:0,pad0:0,pad1:0}),U=a.params(bo,{n:r,items:r,stride:I.stride??r,r:0,flagIndex:0,giant:Ve,maxSteps:Ul,pad0:0}),B={edgeSrc:s.bindings.src,edgeDst:s.bindings.dst,edgeWeight:i??s.bindings.src};for(let H=0;H<Nr;H++){for(const ee of[d,f])w.dispatch(F,w.bind({dst:ee,P:R.binding}),A,[R.offset]);for(const ee of[m,y])ee.dispatch(F,ee.bind({...B,comp:u,bestKey:d,bestEdge:f,P:D.binding}),E,[D.offset]);const Y=a.params(Di,{count:r,counterIndex:H,pad0:0,pad1:0});b.dispatch(F,b.bind({edgeSrc:B.edgeSrc,edgeDst:B.edgeDst,bestEdge:f,comp:u,treeEdge:h,counters:g,P:Y.binding}),A,[Y.offset]);for(let ee=0;ee<k;ee++)v.dispatch(F,v.bind({comp:u,P:U.binding}),I,[U.offset])}C.endPass();const V=C.readback(g.buffer,0,4*Nr);a.flush();const q=await C.submit().readback;n.assertReady(),O=!1,t?.signal?.aborted;const K=new Uint32Array(q,V.offset,Nr);let X=!1;for(const H of K)$+=H,X||=H===0;if(T+=Nr,$>r-1)throw new S("E_VALIDATION",`${an}: ${$} forest edges on ${r} nodes`,{label:`${an}/counters`,message:"a spanning forest has at most n - 1 edges"});if(X)break;if(T>=AT)throw new S("E_VALIDATION",`${an}: still merging after ${T} rounds`,{label:`${an}/rounds`,message:"Boruvka halves the components every round; the device did not"});C=new Pe(n,`${an}/rounds`)}const L=new Uint32Array(r);return await n.readback.read(h.buffer,4*r,L),n.assertReady(),t?.onProgress?.(1,1),IT(e,L,$)}finally{a.dispose()}}const gm=8,ST=2*gm+2;function PT(n,e,t){if(n===void 0)return null;if(n instanceof Float32Array&&n.length===e&&n.buffer instanceof ArrayBuffer)return n;throw new S("E_INVALID_ARGUMENT",`${t}: dest must be a Float32Array of length ${e} over an ArrayBuffer`,{argument:"dest",value:`${n.constructor.name}(${n.length})`,expected:`Float32Array(${e}) over an ArrayBuffer`})}function xT(n,e,t){const r=n.residency.core(e);return sr(r,e.arcCount,n.caps.limits.maxStorageBufferBindingSize,t),r}function Po(n,e){return{buffer:n,offset:0,size:e,window:null}}function wm(n,e){return new S("E_ABORTED",`${n}: the signal was aborted`,e===void 0?{}:{batchId:e})}async function pm(n,e,t,r,o){n.assertReady(),await Lt(n);const s=e.nodeCount,i=r?.dampingFactor??.85,a=r?.maxIterations??100,c=r?.tolerance??1e-6,l=r?.weighted!==!1;if(!Number.isInteger(a)||a<1)throw new S("E_INVALID_ARGUMENT",`${o}: maxIterations must be a positive integer`,{argument:"maxIterations",value:a,expected:"a positive integer"});const u=PT(r?.dest,s,o);if(r?.signal?.aborted)throw wm(o);if(s===0)return r?.onProgress?.(a,a),{scores:u??new Float32Array(0),iterations:0,converged:!0,danglingMass:0,precision:"f32"};const d=xT(n,e,o);if(e.arcCount===0){const b=u??new Float32Array(s);return t===null?b.fill(1/s):b.set(t),r?.onProgress?.(a,a),{scores:b,iterations:0,converged:!0,danglingMass:1,precision:"f32"}}const f=n.residency.view(e,"reverse"),h=Ui(f,f.scalars.arcCount[0]),g=l?void 0:null,w=l?d:{...d,weights:null,hasWeights:!1},p=l?h:{...h,weights:null,hasWeights:!1},m=Mt(n,o,ST);let y=null;try{const b=4*s,v=m.scratch(b,"rankA"),A=m.scratch(b,"rankB"),E=m.scratch(b,"xNorm"),I=m.scratch(b,"outWeightSum"),k=se(s,n.workgroupSize,n.caps),N=yl(k),C=et.byteLength*(1+N),O=m.scratch(C,"partials"),T=m.scratch(et.byteLength,"lastHeader");t!==null&&(y=n.residency.array(t,`${o}/personalization`)),await n.allocator.check();const $=await lm(m,w,{op:"sum",valueSnippet:"v = weight;",tiers:null}),L=await Cl(m,p,{personalization:t!==null,dangling:!0,weights:g,tiers:null}),F=await n.pipelines.kernel(z("pr-scale",{NORM_MODE:0})),M=await n.pipelines.kernel(z("pr-finalize",{NORM_MODE:0})),R=se(1,n.workgroupSize,n.caps),{queue:D}=n.device;D.writeBuffer(v,0,new Float32Array(s).fill(1/s)),D.writeBuffer(A,0,new Float32Array(s));const U=new ArrayBuffer(et.byteLength);et.write(new DataView(U),{firstConverged:Ve,iteration:0}),D.writeBuffer(O,0,U);const B=[Po(v,b),Po(A,b)],V=Po(E,b),W=Po(I,b),q=Po(O,C),K=Po(T,et.byteLength),X={alpha:i,beta:1-i,uniformP:1/s};let H=0,Y=0;for(;;){const ee=Math.min(gm,a-Y),Z=new Pe(n,o);let J=Z.pass("iterations");Y===0&&$.record(J,w,W);const ce=Y+ee===a;for(let me=0;me<ee+(ce?1:0);me++){const De=m.params(Ti,{n:s,groups:N,iteration:Y+me+1,trackConvergence:1,convergeThreshold:c*s}),Ne=1-H;me===ee&&(Z.copy(q,K,et.byteLength),J=Z.pass("convergence"));const He=F.bind({rankIn:B[H],rankPrev:B[Ne],outWeightSum:W,xNorm:V,partials:q,P:De.binding});F.dispatch(J,He,k,[De.offset]);const _n=M.bind({partials:q,P:De.binding});if(M.dispatch(J,_n,R,[De.offset]),me===ee)break;L.record(J,p,{xNorm:V,rankOut:B[Ne],personalization:y?.binding??null,partials:q},X),H=Ne}Z.endPass();const de=Z.readback(O,0,et.byteLength),ne=ce?Z.readback(T,0,et.byteLength):de,ve=Z.readback(B[H].buffer,0,b);m.flush();const ue=Z.submit(),we=await ue.readback;if(Y+=ee,n.assertReady(),r?.signal?.aborted)throw wm(o,ue.id);r?.onProgress?.(Y,a);const he=et.read(new DataView(we),de.offset).firstConverged,ge=he!==Ve;if(ge||Y>=a){const me=u??new Float32Array(s);return me.set(new Float32Array(we,ve.offset,s)),ge&&Y<a&&r?.onProgress?.(a,a),{scores:me,iterations:ge?he:Y,converged:ge,danglingMass:et.read(new DataView(we),ne.offset).danglingMass,precision:"f32"}}}}finally{y?.destroy(),m.dispose()}}function CT(n,e,t){return pm(n,e,null,t,"pageRank")}async function NT(n,e,t,r){const o=e.nodeCount,s=(c,l)=>new S("E_INVALID_ARGUMENT",`personalizedPageRank: personalization must be ${l}`,{argument:"personalization",value:c,expected:l});if(!(t instanceof Float32Array)||t.length!==o)throw s(`${t.constructor.name}(${t.length})`,`a Float32Array of length ${o}`);let i=0;for(let c=0;c<o;c++){const l=t[c];if(!Number.isFinite(l)||l<0)throw s(l,"finite and non-negative in every entry");i+=l}if(o>0&&!(i>0))throw s(i,"a vector whose entries sum to a positive number");const a=new Float32Array(o);for(let c=0;c<o;c++)a[c]=t[c]/i;return pm(n,e,a,r,"personalizedPageRank")}function Fl(n,e,t,r){n.assertReady();const o=e.nodeCount,s=t?.maxIterations??100,i=t?.tolerance??1e-6;if(!Number.isInteger(s)||s<1)throw new S("E_INVALID_ARGUMENT",`${r}: maxIterations must be a positive integer`,{argument:"maxIterations",value:s,expected:"a positive integer"});const a=vN(t?.dest,o,r);if(t?.signal?.aborted)throw Hp(r);return{n:o,maxIterations:s,tolerance:i,weights:t?.weighted===!1?null:void 0,dest:a}}function mm(n,e,t){const r=n??e;if(!Number.isFinite(r))throw new S("E_INVALID_ARGUMENT",`katzCentrality: ${t} must be a finite number`,{argument:t,value:r,expected:"a finite number"});return r}function Bl(n,e,t){let r=0;for(const i of n)r+=t==="sum"?Math.abs(i):i*i;const o=t==="sum"?r:Math.sqrt(r),s=e??n;for(let i=0;i<n.length;i++)s[i]=o>0?n[i]/o:n[i];return s}function ym(n,e,t){return{scores:Bl(n.scores,e,t),iterations:n.iterations,converged:n.converged,precision:"f32"}}function zl(n,e,t){return t?.(e,e),{scores:n??new Float32Array(0),iterations:0,converged:!0,precision:"f32"}}function bm(n,e){const t=n.iterationsRun%2===0?n.iterationsRun:n.iterationsRun-1,r=e.iterationsRun%2===1?e.iterationsRun:e.iterationsRun-1,o=t>=r?n:e;return(Math.max(t,r)===o.iterationsRun?o.scores:o.previous)??o.scores}async function TT(n,e,t){const r="eigenvectorCentrality",o=Fl(n,e,t,r);if(o.n===0)return zl(o.dest,o.maxIterations,t?.onProgress);const s=await Gi(n,o.n,{normMode:2,adjacency:qp(n,e,r),alternate:null,alpha:1,beta:0,uniformP:0,maxIterations:o.maxIterations,tolerance:o.tolerance,weights:o.weights,label:r,signal:t?.signal,onProgress:t?.onProgress});return ym(s,o.dest,"l2")}async function OT(n,e,t){const r="katzCentrality",o=mm(t?.alpha,.1,"alpha"),s=mm(t?.beta,1,"beta"),i=Fl(n,e,t,r);if(i.n===0)return zl(i.dest,i.maxIterations,t?.onProgress);const a=await Gi(n,i.n,{normMode:4,adjacency:Nl(n,e),alternate:null,alpha:o,beta:s,uniformP:1,maxIterations:i.maxIterations,tolerance:i.tolerance,weights:i.weights,label:r,signal:t?.signal,onProgress:t?.onProgress});return ym(a,i.dest,"l2")}async function $T(n,e,t){const r="hits",o=Fl(n,e,t,r),s=2*o.maxIterations;if(o.n===0){const{scores:f,iterations:h,converged:g,precision:w}=zl(o.dest,s,t?.onProgress);return{hubs:f,authorities:new Float32Array(0),iterations:h,converged:g,precision:w}}const i=t?.onProgress,a={normMode:1,alpha:1,beta:0,uniformP:0,maxIterations:o.maxIterations,tolerance:o.tolerance,weights:o.weights,signal:t?.signal},c=qp(n,e,r),l=Nl(n,e),u=await Gi(n,o.n,{...a,adjacency:l,alternate:c,label:`${r}/hub-seeded`,onProgress:i===void 0?void 0:f=>{i(f,s)}}),d=await Gi(n,o.n,{...a,adjacency:c,alternate:l,label:`${r}/authority-seeded`,onProgress:i===void 0?void 0:f=>{i(o.maxIterations+f,s)}});return{hubs:Bl(bm(u,d),o.dest,"sum"),authorities:Bl(bm(d,u),null,"sum"),iterations:Math.max(u.iterations,d.iterations),converged:u.converged&&d.converged,precision:"f32"}}const As="triangleCount",RT=1024;function DT(n,e){return null}function vm(n,e){const t=n.length,r=new Float32Array(t);let o=0,s=0;for(let i=0;i<t;i++){const a=e[i+1]-e[i],c=n[i];if(o+=c,a>=2){const l=a*(a-1)/2;s+=l,r[i]=c/l}}return{perNode:n,total:o/3,coefficient:r,transitivity:s===0?0:o/s}}async function LT(n,e,t){return await MT(n,e,0,t)}async function MT(n,e,t,r){n.assertReady(),await Lt(n);const o=e.nodeCount,s=DT();if(o===0)return vm(s??new Uint32Array(0),new Uint32Array(1));const i=Mt(n,As,RT);try{const a=await dm(n,e,i,!1,As),{graph:c,batch:l}=a,u=n.workgroupSize,d=4*o,f={buffer:i.scratch(d,"counts"),offset:0,size:d,window:null},h=await n.pipelines.kernel(z("fill")),g=l.pass("triangles");let w=null;const p=i.params(Ze,{count:o,value:0,mode:0,pad0:0});if(h.dispatch(g,h.bind({dst:f,P:p.binding}),se(o,u,n.caps),[p.offset]),c.arcCount>0&&c.colIdx!==null&&c.src!==null){const k=c.arcCount/2,N=await n.pipelines.kernel(z("orient-flags")),C=await n.pipelines.kernel(z("tri-intersect",{SEARCH:t})),O=await Bi(i),T=await am(i),$=(K,X)=>({buffer:i.scratch(4*K,X),offset:0,size:4*K,window:null}),L=$(c.arcCount,"orient/flags"),F=$(c.arcCount,"orient/src"),M=$(c.arcCount,"orient/dst"),R=$(o+1,"orient/rowPtr"),D=$(k,"orient/colIdx"),U=$(1,"orient/count"),B=$(1,"orient/flag"),V=se(c.arcCount,u,n.caps),W=i.params(vn,{count:c.arcCount,pad0:0,pad1:0,pad2:0});N.dispatch(g,N.bind({rowPtr:c.rowPtr,colIdx:c.colIdx,src:c.src,flags:L,P:W.binding}),V,[W.offset]),O.record(g,{queue:c.src,flags:L,count:c.arcCount,out:F,outCount:U,outIndex:0}),O.record(g,{queue:c.colIdx,flags:L,count:c.arcCount,out:M,outCount:U,outIndex:0}),T.record(g,{src:F,dst:M,weights:null,count:k,n:o,sortedInput:!0,out:{rowPtr:R,colIdx:D,weights:null,flag:B}}),w=B;const q=i.params(vn,{count:k,pad0:0,pad1:0,pad2:0});C.dispatch(g,C.bind({rowPtr:R,colIdx:D,src:F,counts:f,P:q.binding}),se(k,u,n.caps),[q.offset])}l.endPass();const m=l.readback(f.buffer,0,d),y=l.readback(c.rowPtr.buffer,0,4*(o+1)),b=w===null?null:l.readback(w.buffer,0,4);i.flush();const A=await l.submit().readback;if(n.assertReady(),r?.signal?.aborted,Ll(A,a,As),b!==null&&new Uint32Array(A,b.offset,1)[0]!==0)throw new S("E_VALIDATION",`${As}: the oriented arcs reached cooToCsr out of order`,{label:`${As}/oriented`,message:"the sorted-input precondition of cooToCsr failed on the device"});const E=s??new Uint32Array(o);E.set(new Uint32Array(A,m.offset,o));const I=new Uint32Array(A,y.offset,o+1);return r?.onProgress?.(1,1),vm(E,I)}finally{i.dispose()}}function UT(n){let e=1;for(;e<n;)e*=2;return e}function FT(n){let e=1;for(;e*2<=n;)e*=2;return e}function BT(n,e){const t=s=>e===3?s*s*s:s*s;let r=1;for(;t(r)<n;)r*=2;let o=0;for(;o<r;){const s=Math.floor((o+r)/2);t(s)>=n?r=s:o=s+1}return o}function Un(n,e,t){const r=e===3?t.gridMax3D:t.gridMax2D,o=Math.max($w,FT(Math.max(1,r))),s=Math.min(o,Math.max($w,UT(2*BT(n,e))));let i=1;for(let d=s;d>Rw;d/=2)i++;const a=s**e,c=2**e,l=[0];let u=s;for(let d=0;d+1<i;d++)l.push(l[d]+u**e+(d===0?c:0)),u/=2;return{dim:e,g:s,levels:i,cells:a,outsideCells:c,histWords:a+c+1,levelOffsets:Object.freeze(l),pyramidCells:l[i-1]+Rw**e,deterministic:t.deterministic}}function zT(n){return 16*n.pyramidCells}async function GT(n,e){const t=await n.pipelines.kernel(z("grid-cell-key")),r=e.deterministic?{kind:"radix",radix:await Sl(n),histogram:await om(n),scan:await Or(n)}:{kind:"counting",counting:await XN(n)};return new WT(n,e,t,r)}class WT{constructor(e,t,r,o){this.bound=null,this.dispatches=0,this.scope=e,this.spec=t,this.cellKey=r,this.path=o}get lastDispatches(){return this.dispatches}bind(e){const t=Math.floor(e.cellKey.size/4);if(t<1)throw new S("E_INVALID_ARGUMENT","gridBuild: cellKey must hold at least one word",{argument:"cellKey",value:e.cellKey.size,expected:4});const r=this.path.kind==="radix"?zi(t,this.scope.workgroupSize)/4:this.spec.histWords;this.bound={bindings:e,capacity:t,scratchA:this.scratch(r,"grid/sort-scratch-a"),scratchB:this.scratch(r,"grid/sort-scratch-b")}}record(e,t,r,o){const{bound:s}=this;if(s===null)throw new S("E_NOT_LOADED","gridBuild: record() before bind()",{argument:"bind"});if(!Number.isSafeInteger(t)||t<1||t>s.capacity)throw new S("E_INVALID_ARGUMENT","gridBuild: n must be an integer in [1, the capacity]",{argument:"n",value:t,expected:s.capacity});const i=o??"G3",a=s.bindings,c=this.cellKey.bind({pos:a.pos,S:a.state,cellKey:a.cellKey,cellVal:a.cellVal,P:a.params});if(this.cellKey.dispatch(e,c,se(t,this.scope.workgroupSize,this.scope.caps),[r]),this.dispatches=1,i==="G1")return;const{histWords:l}=this.spec;if(this.path.kind==="counting"){const{counting:h}=this.path,g={hist:a.cellHist,cursor:s.scratchA};h.record(e,a.cellKey,t,l,g,a.sortedIdx,a.cellStart),this.dispatches+=h.lastDispatches;return}const{radix:u,histogram:d,scan:f}=this.path;u.record(e,a.cellKey,a.cellVal,t,$k,{keys:a.sortedKey,vals:a.sortedIdx,hist:s.scratchA,offsets:s.scratchB}),this.dispatches+=u.lastDispatches,i!=="G2"&&(d.record(e,a.cellKey,t,l,a.cellHist),f.record(e,a.cellHist,l,a.cellStart),this.dispatches+=d.lastDispatches+f.lastDispatches)}scratch(e,t){const r=4*Math.max(1,e);return{buffer:this.scope.scratch(r,t),offset:0,size:r,window:null}}}const Gl=34359738337,VT=185852,jT=1;class qT{constructor(e){this.seed=e===null||e===0||Number.isNaN(e)?Math.floor(Math.random()*1e6):e,this.state=this.seed%Gl}next(){return this.state=(VT*this.state+jT)%Gl,this.state/Gl}}function HT(n){const e=[0,0,0];if(n===null)return e;for(let t=0;t<3&&t<n.length;t++){const r=n[t];if(!Number.isFinite(r))throw new S("E_INVALID_ARGUMENT",`center[${t}] is not finite`,{argument:"center",value:r,expected:"finite components"});e[t]=r}return e}function KT(n,e,t,r,o,s,i){const a=n.nodeCount;if(r!==2&&r!==3)throw new S("E_INVALID_ARGUMENT",`dim must be 2 or 3, got ${String(r)}`,{argument:"dim",value:r,expected:"2 or 3"});if(e.length!==3*a)throw new S("E_INVALID_ARGUMENT",`positions has ${e.length} entries, expected ${3*a}`,{argument:"positions",value:e.length,expected:3*a});if(!Number.isFinite(o)||o<=0)throw new S("E_INVALID_ARGUMENT",`scale must be a finite number > 0, got ${o}`,{argument:"scale",value:o,expected:"a finite number > 0"});const c=HT(s),l=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],u=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];let d=0,f=0;for(let y=0;y<a;y++){let b=!0;for(let v=0;v<r;v++){const A=e[3*y+v];Number.isFinite(A)?(A<l[v]&&(l[v]=A),A>u[v]&&(u[v]=A)):b=!1}b?d++:f++}if(f===0)return;const h=i==="fr"?0:-1,g=1,w=[h,h,h],p=[g,g,g];if(d>0){for(let y=0;y<r;y++)if(Number.isFinite(l[y])&&Number.isFinite(u[y])&&(w[y]=(l[y]-c[y])/o,p[y]=(u[y]-c[y])/o,w[y]===p[y])){const b=(g-h)/2;w[y]-=b,p[y]+=b}}const m=new qT(t);for(let y=0;y<a;y++){let b=!1;for(let v=0;v<r;v++)Number.isFinite(e[3*y+v])||(b=!0);if(b){for(let v=0;v<r;v++){const A=3*y+v;if(!Number.isFinite(e[A])){const E=m.next(),I=w[v]+E*(p[v]-w[v]);e[A]=I*o+c[v]}}r===2&&(e[3*y+2]=c[2])}}}const YT=[["n",1],["dim",1],["flags",1],["iterationIndex",1],["seed",1],["scale",1],["center",4],["settleThreshold",1]],XT=[["centroid",4],["min",4],["max",4],["rmsRadius",1],["radius",1],["meanDisplacement",1],["iteration",1],["settledCount",1]],QT=new Set(["positions","scenePositions","fixed","partials","state","trace"]),JT=new Set(["fixed","trace","cellKey","cellVal","sortedKey","sortedIdx","cellHist","cellStart","hubList","hubCounters"]),ZT="toScene";let Am=0;function be(n,e,t,r){return new S("E_INVALID_ARGUMENT",r,{argument:n,value:e,expected:t})}function Em(n){return new S("E_DISPOSED",`${n} is disposed`,{label:n})}function xo(n){return n instanceof Error?n:new Error(typeof n=="string"?n:"unknown error")}function Wl(n,e){return n[e]}function Vl(n){switch(n){case"u32":case"i32":case"f32":return 1;case"vec2f":case"vec2u":return 2;case"vec4f":case"vec4u":return 4;default:throw be("type",n,"a UniformFieldType","unknown uniform field type")}}function _m(n,e){for(const[t,r]of n.fields)if(t===e)return r;return null}function Im(n,e){const t=_m(n,e);if(t===null)throw be("field",e,n.fields.map(r=>r[0]),`block ${n.name} has no field ${e}`);return t}function km(n,e,t){for(const[r,o]of e){const s=_m(n,r);if(s===null)throw be(t,r,e.map(i=>i[0]),`${t} block ${n.name} must declare ${r}`);if(Vl(s)!==o)throw be(t,r,`a field of width ${o}`,`${t}.${r} must have width ${o}`)}}function Sm(n){return JSON.stringify(Object.keys(n).sort().map(e=>[e,n[e]]))}function Pm(n,e){return{...n,msPerIteration:e}}function eO(n){return typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function jl(n){const e=n.scale??Cr.scale;if(!Number.isFinite(e)||e<=0)throw be("scale",e,"a finite number > 0",`scale must be a finite number > 0, got ${e}`);return e}function ql(n){const e=[0,0,0],{center:t}=n;if(t===void 0)return e;for(let r=0;r<3&&r<t.length;r++){const o=t[r];if(!Number.isFinite(o))throw be("center",o,"finite components",`center[${r}] is not finite`);e[r]=o}return e}function Es(n,e){return n.repulsion==="exact"?"exact":n.repulsion==="grid"?"grid":e<=n.exactMaxNodes?"exact":"grid"}function _s(n,e){return{buffer:n,offset:0,size:e,window:null}}class tO{constructor(e){this.shadow=new Map,this.queued=new Map,this.block=e,this.reset()}set(e,t){const r=Vl(Im(this.block,e));if(!(r===1?typeof t=="number":typeof t!="number"&&t.length===r))throw be("value",t,`a value of width ${r}`,`state field ${e} takes a value of width ${r}`);this.shadow.set(e,t),this.queued.set(e,t)}get(e){const t=this.shadow.get(e);if(t===void 0)throw be("field",e,this.block.fields.map(r=>r[0]),`state block has no field ${e}`);return t}reset(){this.shadow.clear(),this.queued.clear();const e=this.block.read(new DataView(new ArrayBuffer(this.block.byteLength)));for(const[t,r]of Object.entries(e))this.shadow.set(t,r)}headerBytes(){const e=new ArrayBuffer(this.block.byteLength);return this.block.write(new DataView(e),Object.fromEntries(this.shadow)),e}absorb(e){for(const[t,r]of Object.entries(this.block.read(e)))this.queued.has(t)||this.shadow.set(t,r)}takeQueued(){const e=[...this.queued.keys()];return this.queued.clear(),e}clearQueued(){this.queued.clear()}}function nO(n,e){let t=()=>{},r=()=>{};const o=new Promise((s,i)=>{t=s,r=i});return{k:n,generation:e,promise:o,resolve:()=>{t()},reject:s=>{r(s)},id:0,submitted:null,stale:!1,startedAt:0,sceneOffset:0,stateOffset:0,profile:null}}class Hl{constructor(e,t,r,o,s){if(this.overrideList=new Map,this.pending=[],this.stateValue="created",this.generationValue=0,this.snapshot=null,this.serial=null,this.owner=null,this.n=0,this.scale=1,this.center=[0,0,0],this.buffers=null,this.core=null,this.resources=null,this.weightsUpload=null,this.ready=Promise.resolve(),this.submitChain=Promise.resolve(),this.fixedWords=new Uint32Array(0),this.fixedDirty=!1,this.iterationsSubmitted=0,this.iterationsDoneValue=0,this.settledCountValue=0,this.settledValue=!1,this.firstPending=!0,this.statsValue=null,this.lastPassTimingsValue=null,this.lastSubmittedBatchIdValue=0,this.reheatedAfterBatchId=0,this.coalescedValue=0,this.torndown=!1,e.assertReady(),km(t.params,YT,"model.params"),km(t.state,XT,"model.state"),t.params.byteLength>Vt)throw be("model.params",t.params.byteLength,`<= ${Vt} bytes`,"the params block must fit one ring slot");if(t.state.byteLength>jt)throw be("model.state",t.state.byteLength,`<= ${jt} bytes`,"the state block must fit the state header");if(t.stages.length===0)throw be("model.stages",t.stages,"at least one stage name","a model declares its stages");const i=r.maxInFlight??Cr.maxInFlight;if(!Number.isInteger(i)||i<1)throw be("maxInFlight",i,"an integer >= 1",`maxInFlight must be an integer >= 1, got ${i}`);const a=r.dim??Cr.dim;if(a!==2&&a!==3)throw be("dim",a,"2 or 3",`dim must be 2 or 3, got ${String(a)}`);jl(r),ql(r),Am++,this.ctx=e,this.model=t,this.tuning=o,this.resolveOptions=s,this.optionsValue=r,this.maxInFlight=i,this.dimValue=a,this.tierValue=o.repulsion==="grid"?"grid":"exact",this.label=`${t.kind}#${Am}`,this.traceBytes=t.trace.byteLength,this.writer=new tO(t.state),this.ring=new _l(e.device,e.allocator,(i+1)*Rt,`${this.label}/ring`),this.unregisterLost=e.onLost(c=>{this.onDeviceLost(c)}),e.debug.inspect&&(this.inspect=c=>this.inspectBuffer(c),this.debugRunStages=c=>this.runStages(c))}get state(){return this.stateValue}get options(){return this.optionsValue}get tier(){return this.tierValue}get lastPassTimings(){return this.lastPassTimingsValue}get generation(){return this.generationValue}get nodeCount(){return this.n}get dim(){return this.dimValue}get settled(){return this.settledValue}get inFlight(){return this.pending.length}get iterationsDone(){return this.iterationsDoneValue}get stats(){if(this.statsValue!==null)return this.statsValue;const e=new DataView(this.writer.headerBytes()),t=new DataView(new ArrayBuffer(0));return Pm(this.model.readStats(e,t),null)}get overrides(){return this.overrideList}get lastSubmittedBatchId(){return this.lastSubmittedBatchIdValue}get coalesced(){return this.coalescedValue}load(e,t){if(this.assertNotDisposed(),this.ctx.assertReady(),e.directed)throw new S("E_SNAPSHOT","a layout needs an undirected snapshot: pass toUndirected().snapshot",{reason:"directed",serial:e.serial});const r=e.nodeCount;if(r>rl)throw new S("E_TOO_LARGE",`${r} nodes exceed ${rl} (the third partials level is P4)`,{needed:r,limit:rl,path:"partials",algorithm:this.model.kind});if(t.length!==3*r)throw be("positions",t.length,3*r,`positions has ${t.length} entries, expected ${3*r}`);if(eO(t.buffer))throw be("positions","SharedArrayBuffer","an ArrayBuffer-backed Float32Array","positions must not be backed by a SharedArrayBuffer");const o=jl(this.optionsValue),s=ql(this.optionsValue),i=Es(this.tuning,r),a=16*r;if(a>this.ctx.caps.limits.maxBufferSize)throw new S("E_TOO_LARGE",`${a} bytes of positions exceed maxBufferSize`,{needed:a,limit:this.ctx.caps.limits.maxBufferSize,path:"positions",algorithm:this.model.kind});let c=null,l=null,u=null;if(r>0){if(c=this.ctx.residency.core(e),c.plan==="windowed")throw new S("E_TOO_LARGE","a windowed core cannot be walked by the layout kernels until P4",{needed:e.arcCount,limit:this.ctx.caps.limits.maxStorageBufferBindingSize,path:"windowed",algorithm:this.model.kind});if(e.degreeOrder().segmentOffsets[2]>0&&(l=FC(this.ctx.residency.view(e,"degreeOrder"))),u=this.model.inputs(e,this.optionsValue),u.mass.length!==r)throw be("nodeMass",u.mass.length,r,`the model resolved ${u.mass.length} masses for ${r} nodes`);const m=Math.ceil(r/32);if(u.fixed!==void 0&&u.fixed!==null&&u.fixed.length<m)throw be("fixed",u.fixed.length,m,`the model resolved a fixed mask of ${u.fixed.length} words, ${m} needed for ${r} nodes`)}this.generationValue++,this.discardPending();const d=this.buffers===null||r!==this.n||e.serial!==this.serial;if(this.snapshot=e,this.serial=e.serial,this.owner=t,this.n=r,this.tierValue=i,this.scale=o,this.center=s,this.core=c,this.iterationsSubmitted=0,this.iterationsDoneValue=0,this.settledCountValue=0,this.firstPending=!0,this.statsValue=null,this.writer.reset(),d&&(this.destroyBuffers(),this.overrideList.clear(),this.fixedWords=At(r),this.fixedDirty=!1),u?.fixed!==void 0&&u.fixed!==null&&(this.fixedWords.set(u.fixed.subarray(0,Math.ceil(r/32))),this.fixedDirty=!0),r===0||c===null||u===null){this.weightsUpload=null,this.resources=null,this.ready=this.ready.catch(()=>{}),this.settledValue=!0,this.stateValue="loaded";return}const f=d?this.allocate(r):this.requireBuffers();d||this.clearKept(f),this.buffers=f;const h=this.model.kind==="fruchtermanReingold"?"fr":"fa2";KT(e,t,this.optionsValue.seed??null,this.dimValue,o,s,h),this.uploadPositions(f,t,u.mass);const g=this.resolveWeightsBinding(e,c,u.weights),w={...this.model.overrides(this.optionsValue),...Ct(c,l?.perm??null,g)},p=this.makeResources(c,l,g,f);this.resources=p,this.startBind(p,w),this.settledValue=!1,this.stateValue="loaded"}step(e){if(this.stateValue==="created")return Promise.reject(new S("E_NOT_LOADED",`${this.label}: load() first`,{state:"created"}));if(this.stateValue==="disposed")return Promise.reject(Em(this.label));try{this.ctx.assertReady()}catch(s){return Promise.reject(xo(s))}const{snapshot:t}=this;if(t!==null&&this.ctx.residency.isReleased(t.serial))return Promise.reject(new S("E_RELEASED",`snapshot ${t.serial} was released while ${this.label} used it`,{serial:t.serial}));const r=e??this.optionsValue.iterationsPerStep??Cr.iterationsPerStep;if(!Number.isInteger(r)||r<1||r>Rt)return Promise.reject(be("iterations",r,`an integer in [1, ${Rt}]`,`step(${r}): iterations must be an integer in [1, ${Rt}]`));if(this.settledValue||this.n===0)return Promise.resolve();if(this.pending.length>=this.maxInFlight)return this.coalescedValue++,this.pending[0].promise;const o=nO(r,this.generationValue);return this.pending.push(o),this.submitChain=this.submitChain.then(()=>this.submitBatch(o)),o.promise}async flush(){for(;this.pending.length>0;)await Promise.allSettled(this.pending.map(e=>e.promise))}async run(e){this.assertNotDisposed();const t=e?.batch??8;if(!Number.isInteger(t)||t<1||t>Rt)throw be("batch",t,`an integer in [1, ${Rt}]`,"run(): batch must be an integer in [1, MAX_ITERATIONS_PER_STEP]");const r=e?.maxIter??this.iterationBudget();if(Number.isNaN(r)||r<0)throw be("maxIter",r,"a number >= 0","run(): maxIter must be >= 0");const o=e?.signal,s=()=>{this.discardPending()};if(o!==void 0){if(o.aborted)throw this.abortedError();o.addEventListener("abort",s,{once:!0})}try{for(;!this.settled&&this.iterationsDoneValue<r;){if(o?.aborted===!0)throw this.abortedError();const i=Math.min(t,r-this.iterationsDoneValue);await this.step(i)}if(o?.aborted===!0)throw this.abortedError();return this.stats}finally{o?.removeEventListener("abort",s)}}setFixed(e){this.assertLoaded();const{n:t}=this,r=Math.ceil(t/32);if(e.length<r)throw be("mask",e.length,r,`setFixed: the mask has ${e.length} words, ${r} needed for ${t} nodes`);let o=!1;for(let s=0;s<r&&!o;s++){if(this.fixedWords[s]===e[s])continue;const i=Math.min(t,s*32+32);for(let a=s*32;a<i;a++)if(_e(this.fixedWords,a)&&!_e(e,a)){o=!0;break}}this.fixedWords.set(e.subarray(0,r)),this.fixedDirty=!0,o&&this.reheat()}setPosition(e,t,r,o){this.assertLoaded();const{n:s}=this;if(!Number.isInteger(e)||e<0||e>=s)throw be("index",e,`an integer in [0, ${s})`,`setPosition(${e}): index out of range`);if(!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(o))throw be("position",[t,r,o],"finite coordinates","setPosition: coordinates must be finite");const{owner:i,buffers:a}=this;if(i===null||a===null)throw new S("E_NOT_LOADED",`${this.label}: load() first`,{state:this.stateValue});i[3*e]=t,i[3*e+1]=r,i[3*e+2]=o;const[c,l,u]=this.center,d=new Float32Array([(t-c)/this.scale,(r-l)/this.scale,this.dimValue===2?0:(o-u)/this.scale]);this.ctx.device.queue.writeBuffer(a.positions,16*e,d),this.overrideList.set(e,this.lastSubmittedBatchIdValue),this.reheat()}reheat(){this.assertNotDisposed(),this.iterationsDoneValue=0,this.settledCountValue=0,this.reheatedAfterBatchId=this.lastSubmittedBatchIdValue,this.writer.set("settledCount",0),this.model.onReheat(this.writer),this.settledValue=this.computeSettled()}setParams(e){this.assertNotDisposed();const t=this.optionsValue,{dim:r,maxInFlight:o}=e;if(r!==void 0&&r!==this.dimValue)throw be("dim",r,this.dimValue,"dim is fixed at construction; graphty-element re-creates the engine on a view-mode switch (spec 7.13)");if(o!==void 0&&o!==this.maxInFlight)throw be("maxInFlight",o,this.maxInFlight,"maxInFlight is fixed at construction (the uniform ring is sized by it)");const s=Wl(e,"nodeSize");if(s!=null)throw new S("E_UNSUPPORTED","nodeSize (adjustSizes) is deferred (spec 7.14)",{option:"nodeSize",hint:"leave nodeSize null; the size correction ships in a later slice"});const i=this.resolveOptions(e,t),a=jl(i),c=ql(i),l=Sm(this.model.overrides(t)),u=Sm(this.model.overrides(i));this.optionsValue=i,this.scale=a,this.center=c;const{resources:d,core:f}=this;if(this.stateValue==="loaded"&&d!==null&&f!==null&&l!==u){const h={...this.model.overrides(i),...Ct(f,d.tiers?.perm??null,d.weights)};this.startBind(d,h)}this.model.onSetParams(e,this.writer),this.reheat()}dispose(){this.stateValue!=="disposed"&&(this.stateValue="disposed",this.teardown())}async submitBatch(e){try{await this.ready,await this.ctx.allocator.check()}catch(r){if(this.finish(e),this.isStale(e)){e.resolve();return}xi(r,"E_OUT_OF_MEMORY")&&this.outOfMemory(),e.reject(xo(r));return}if(this.isStale(e)){this.finish(e),e.resolve();return}let t;try{t=this.recordAndSubmit(e)}catch(r){this.finish(e),e.reject(xo(r));return}t.readback.then(r=>{this.onLanded(e,r)},r=>{this.onFailed(e,r)})}recordAndSubmit(e){const t=this.requireBuffers(),{k:r}=e,{device:o}=this.ctx;this.fixedDirty&&(o.queue.writeBuffer(t.fixed,0,this.fixedWords),this.fixedDirty=!1),this.flushStateWrites(t.state);const s=this.ring.reserve(r);for(let h=0;h<r;h++){const g=h===0&&this.firstPending?ol:0;this.ring.write(s+h,this.model.params,this.paramsForSlot(this.iterationsSubmitted+h,h,g))}this.ring.flush();const i=new Pe(this.ctx,`${this.label}/batch`,this.generationValue),a=this.lastIterationStage();for(let h=0;h<r;h++)this.model.recordIteration(i,s+h,this.tierValue,h===r-1?void 0:a);i.endPass();const c=i.readback(t.scene,0,12*this.n),l=i.readback(t.state,0,jt+r*this.traceBytes),{profiler:u}=this.ctx,d=u===null?null:u.resolveInto(i),f=i.submit();return e.submitted=f,e.id=f.id,e.sceneOffset=c.offset,e.stateOffset=l.offset,e.profile=d,e.startedAt=performance.now(),this.lastSubmittedBatchIdValue=f.id,this.iterationsSubmitted+=r,this.firstPending=!1,f}onLanded(e,t){this.finish(e);const{owner:r}=this;if(this.isStale(e)||r===null){e.resolve();return}try{const{k:o}=e,{n:s}=this,i=Math.max(e.sceneOffset+12*s,e.stateOffset+jt+o*this.traceBytes);if(t.byteLength<i){e.resolve();return}this.copyScene(r,t,e);const a=new DataView(t,e.stateOffset,jt),c=new DataView(t,e.stateOffset+jt,o*this.traceBytes);this.writer.absorb(a);const l=this.model.state.readField(a,"settledCount");if(typeof l!="number")throw be("settledCount",l,"a scalar","settledCount must be a scalar field");const u=this.batchMilliseconds(e,t);this.statsValue=Pm(this.model.readStats(a,c),u/o),this.iterationsDoneValue+=o,this.settledCountValue=e.id<=this.reheatedAfterBatchId?0:l,this.settledValue=this.computeSettled(),e.resolve()}catch(o){e.reject(xo(o))}}onFailed(e,t){if(this.finish(e),xi(t,"E_ABORTED")&&this.isStale(e)){e.resolve();return}if(this.ctx.state==="lost"&&!xi(t,"E_DEVICE_LOST")){e.reject(new S("E_DEVICE_LOST","the device was lost while the batch was in flight",{reason:"unknown",message:xo(t).message}));return}e.reject(xo(t))}copyScene(e,t,r){const{n:o}=this,s=new Float32Array(t,r.sceneOffset,3*o);if(this.overrideList.size===0){e.set(s);return}for(let i=0;i<o;i++){const a=this.overrideList.get(i);a!==void 0&&a>=r.id||(e[3*i]=s[3*i],e[3*i+1]=s[3*i+1],e[3*i+2]=s[3*i+2])}for(const[i,a]of this.overrideList)a<r.id&&this.overrideList.delete(i)}batchMilliseconds(e,t){const{profiler:r}=this.ctx;if(r!==null&&e.profile!==null){const o=r.timings(t,e.profile);if(this.lastPassTimingsValue=o,o.length>0&&!r.partial(e.profile)){let s=0;for(const i of o)s+=i.ns;return s/1e6}}return performance.now()-e.startedAt}isStale(e){return e.stale||this.stateValue!=="loaded"||e.generation!==this.generationValue}finish(e){const t=this.pending.indexOf(e);t>=0&&this.pending.splice(t,1)}discardPending(){for(const e of this.pending)e.stale=!0,e.submitted?.discard()}outOfMemory(){this.discardPending(),this.destroyBuffers(),this.ctx.allocator.reset(),this.settledValue=!1,this.stateValue="created"}abortedError(){return new S("E_ABORTED",`${this.label}: run() aborted by the signal`,{batchId:this.lastSubmittedBatchIdValue})}paramsForSlot(e,t,r){const[o,s,i]=this.center,a=this.model.paramsFor(e,this.optionsValue),c=typeof a.flags=="number"?a.flags:0,l={n:this.n,dim:this.dimValue,flags:r|c,iterationIndex:t,seed:this.seedU32(),scale:this.scale,center:[o,s,i,0],settleThreshold:this.settleThreshold()};return{...a,...l}}seedU32(){const{seed:e}=this.optionsValue;return e==null||!Number.isFinite(e)?0:Math.floor(Math.abs(e))%4294967296}flushStateWrites(e){const t=this.writer.takeQueued();if(t.length===0)return;const r=this.writer.headerBytes(),o=this.model.state;for(const s of t){const i=o.offsetOf(s),a=4*Vl(Im(o,s));this.ctx.device.queue.writeBuffer(e,i,r,i,a)}}lastIterationStage(){const e=this.model.stages.indexOf(ZT);if(!(e<=0))return this.model.stages[e-1]}settleThreshold(){return this.optionsValue.settleThreshold??Cr.settleThreshold}settleWindow(){return this.optionsValue.settleWindow??Cr.settleWindow}iterationBudget(){const e=Wl(this.optionsValue,"maxIter");if(typeof e=="number")return e;const t=Wl(this.optionsValue,"iterations");return typeof t=="number"?t:Number.POSITIVE_INFINITY}computeSettled(){return this.stateValue!=="loaded"?!1:this.n===0||this.iterationsDoneValue>=this.iterationBudget()||this.settledCountValue>=this.settleWindow()}allocate(e){const{allocator:t}=this.ctx,{label:r}=this,o=Math.ceil(e/this.ctx.workgroupSize),s=Rt*this.traceBytes,i=Se.STORAGE|Se.COPY_SRC|Se.COPY_DST,a=t.createBuffer({label:`${r}/positions`,size:16*e,usage:i}),c=t.createBuffer({label:`${r}/scenePositions`,size:12*e,usage:Se.STORAGE|Se.COPY_SRC}),l=t.createBuffer({label:`${r}/fixed`,size:4*Math.ceil(e/32),usage:i}),u=t.createBuffer({label:`${r}/partials`,size:Cw*o,usage:i}),d=t.createBuffer({label:`${r}/state`,size:jt+s,usage:i}),f=new Map;f.set("positions",_s(a,16*e)),f.set("scenePositions",_s(c,12*e)),f.set("fixed",_s(l,4*Math.ceil(e/32))),f.set("partials",_s(u,Cw*o)),f.set("state",{buffer:d,offset:0,size:jt,window:null}),f.set("trace",{buffer:d,offset:jt,size:s,window:null});const h=new Map;for(const g of this.model.buffers(e,this.dimValue)){if(QT.has(g.name)||f.has(g.name))throw be("BufferSpec.name",g.name,"a name no other buffer uses",`BufferSpec "${g.name}" reuses a buffer name`);if(!Number.isInteger(g.byteLength)||g.byteLength<=0||g.byteLength%4!==0)throw be("BufferSpec.byteLength",g.byteLength,"a positive multiple of 4",`BufferSpec "${g.name}" has byteLength ${g.byteLength}`);if(g.zero&&(g.usage&Se.COPY_DST)===0)throw be("BufferSpec.usage",g.usage,"COPY_DST on a zero: true spec",`BufferSpec "${g.name}" is zero: true but lacks COPY_DST`);const w=t.createBuffer({label:`${r}/${g.name}`,size:g.byteLength,usage:g.usage});h.set(g.name,{buffer:w,spec:g}),f.set(g.name,_s(w,g.byteLength))}return{positions:a,scene:c,fixed:l,partials:u,state:d,model:h,bindings:f,traceRegionBytes:s}}clearKept(e){const{device:t}=this.ctx,r=t.createCommandEncoder({label:`${this.label}/clear`});r.clearBuffer(e.partials),r.clearBuffer(e.state,jt,e.traceRegionBytes);for(const{buffer:o,spec:s}of e.model.values())s.zero&&r.clearBuffer(o);t.queue.submit([r.finish()])}destroyBuffers(){const{buffers:e}=this;if(e===null)return;this.buffers=null,this.resources=null;const t=[e.positions,e.scene,e.fixed,e.partials,e.state];for(const{buffer:r}of e.model.values())t.push(r);this.afterInFlight(()=>{const{allocator:r}=this.ctx;for(const o of t)r.destroy(o)})}afterInFlight(e){const t=[];for(const r of this.pending)r.submitted!==null&&t.push(r.submitted.readback.catch(()=>{}));if(t.length===0){e();return}Promise.all(t).then(e,e)}requireBuffers(){const{buffers:e}=this;if(e===null)throw new S("E_NOT_LOADED",`${this.label}: load() first`,{state:this.stateValue});return e}uploadPositions(e,t,r){const{n:o,scale:s}=this,[i,a,c]=this.center,l=new Float32Array(4*o);for(let A=0;A<o;A++)l[4*A]=(t[3*A]-i)/s,l[4*A+1]=(t[3*A+1]-a)/s,l[4*A+2]=this.dimValue===2?0:(t[3*A+2]-c)/s,l[4*A+3]=r[A];this.ctx.device.queue.writeBuffer(e.positions,0,l);let u=0,d=0,f=0;const h=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],g=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(let A=0;A<o;A++){const E=l[4*A],I=l[4*A+1],k=l[4*A+2];u+=E,d+=I,f+=k,h[0]=Math.min(h[0],E),h[1]=Math.min(h[1],I),h[2]=Math.min(h[2],k),g[0]=Math.max(g[0],E),g[1]=Math.max(g[1],I),g[2]=Math.max(g[2],k)}const w=u/o,p=d/o,m=f/o;let y=0,b=0;for(let A=0;A<o;A++){const E=l[4*A]-w,I=l[4*A+1]-p,k=l[4*A+2]-m,N=E*E+I*I+k*k;y+=N,b=Math.max(b,N)}const{writer:v}=this;v.set("iteration",0),v.set("settledCount",0),v.set("meanDisplacement",0),v.set("centroid",[w,p,m,0]),v.set("min",[h[0],h[1],h[2],0]),v.set("max",[g[0],g[1],g[2],0]),v.set("rmsRadius",Math.sqrt(y/o)),v.set("radius",Math.sqrt(b)),this.model.onLoad(v),this.ctx.device.queue.writeBuffer(e.state,0,v.headerBytes()),v.clearQueued()}resolveWeightsBinding(e,t,r){if(r.source==="arcs")return this.weightsUpload=null,t.weights;if(r.source==="none"||r.data===null||r.column===null)return this.weightsUpload=null,null;const o=this.weightsUpload,i=o!==null&&o.serial===e.serial&&o.column===r.column&&o.version===r.column.version&&o.data.length===r.data.length&&o!==null?o.data:r.data,a=this.ctx.residency.array(i,"weights",e);return this.weightsUpload={serial:e.serial,column:r.column,version:r.column.version,data:i,upload:a},a.binding}makeResources(e,t,r,o){const{bindings:s}=o;return{device:this.ctx.device,caps:this.ctx.caps,pipelines:this.ctx.pipelines,core:e,tiers:t,weights:r,n:this.n,dim:this.dimValue,tier:this.tierValue,ring:this.ring,pool:this.ctx.pool,buffer:i=>{const a=s.get(i);if(a===void 0)throw be("name",i,[...s.keys()],`no simulation buffer named "${i}"`);return a}}}startBind(e,t){const r=this.generationValue,o=()=>this.compileAndBind(e,t,r),s=this.ready.catch(()=>{}).then(o);s.catch(()=>{}),this.ready=s}async compileAndBind(e,t,r){await Lt(this.ctx);const o=this.ctx.caps.features.has("subgroups");await this.ctx.pipelines.warm(this.model.specs(t,o)),!(this.stateValue!=="loaded"||r!==this.generationValue)&&await this.model.bind(e,t)}async inspectBuffer(e){this.assertLoaded();const{buffers:t}=this,r=t?.bindings.get(e);if(t===null||r===void 0)throw be("name",e,t===null?[]:[...t.bindings.keys()],`inspect("${e}"): no such buffer`);await this.flush();const o=await this.ctx.readback.read(r.buffer,r.size,void 0,r.offset);return JT.has(e)?new Uint32Array(o):new Float32Array(o)}async runStages(e){if(this.assertLoaded(),!this.model.stages.includes(e))throw be("upTo",e,[...this.model.stages],`debugRunStages("${e}"): not a stage of ${this.model.kind}`);if(this.n===0)return;await this.flush(),await this.ready,await this.ctx.allocator.check(),this.assertLoaded();const t=this.requireBuffers(),{device:r}=this.ctx;this.fixedDirty&&(r.queue.writeBuffer(t.fixed,0,this.fixedWords),this.fixedDirty=!1),this.flushStateWrites(t.state);const o=this.ring.reserve(1);this.ring.write(o,this.model.params,this.paramsForSlot(this.iterationsSubmitted,0,this.firstPending?ol:0)),this.ring.flush();const s=new Pe(this.ctx,`${this.label}/debug`,this.generationValue);this.model.recordIteration(s,o,this.tierValue,e),s.endPass(),s.readback(t.state,0,jt);const i=s.submit();this.lastSubmittedBatchIdValue=i.id,await i.readback}onDeviceLost(e){if(this.stateValue==="disposed")return;const t=new S("E_DEVICE_LOST",`device lost (${e.reason}): ${e.message}`,{reason:e.reason,message:e.message}),r=this.pending.splice(0);this.stateValue="disposed";for(const o of r)o.stale=!0,o.reject(t);this.teardown()}teardown(){this.torndown||(this.torndown=!0,this.discardPending(),this.destroyBuffers(),this.afterInFlight(()=>{this.ring.destroy(),this.model.dispose?.()}),this.ctx.state==="ready"&&this.ctx.pool.trim(),this.unregisterLost(),this.core=null,this.snapshot=null,this.owner=null,this.weightsUpload=null)}assertNotDisposed(){if(this.stateValue==="disposed")throw Em(this.label)}assertLoaded(){if(this.stateValue==="created")throw new S("E_NOT_LOADED",`${this.label}: load() first`,{state:"created"});this.assertNotDisposed()}}async function Kl(n,e){const{n:t,tiers:r,pipelines:o,caps:s}=n,i=r?.segmentOffsets,a=i?.[1]??0,c=i?.[2]??0,l=[{tier:2,rows:a},{tier:1,rows:c-a},{tier:0,rows:t-c}],u=[];for(const{tier:d,rows:f}of l){if(d!==0&&f<=0)continue;const h=await o.kernel(z("fa2-attraction",{...e,TIER:d})),g=h.workgroupSize;if(d!==0&&g<Mn)throw new S("E_UNSUPPORTED",`fa2-attraction: the mid tier folds ${Mn} lanes per row, more than the workgroup size ${g}`,{feature:"fa2-attraction.tiers"});if(f<=0)continue;let w=g;d===2?w=1:d===1&&(w=g/Mn),u.push([h,se(f,w,s)])}return{kernels:u}}function rO(n,e,t){const{core:r,tiers:o,weights:s}=e,i={...on(r,o?.perm??null,s),pos:t.pos,force:t.force,P:t.params};return{kernels:n.kernels.map(([a,c])=>[a,a.bind(i),c])}}function oO(n,e,t){for(const[r,o,s]of e.kernels)r.dispatch(n,o,s,[t])}const sO=12,xm="fillParams",iO=4294967296;function ji(n){return n===null?"null":typeof n=="number"||typeof n=="boolean"||typeof n=="string"?String(n):n===void 0?"undefined":typeof n=="object"&&"length"in n&&typeof n.length=="number"?`[${n.length} values]`:typeof n}function dt(n,e,t){return new S("E_INVALID_ARGUMENT",`${n} must be ${t}; got ${ji(e)}`,{argument:n,value:e,expected:t})}function ke(n,e,t,r,o){const s=e===void 0?t:e;if(typeof s!="number"||!Number.isFinite(s)||!r(s))throw dt(n,s,o);return s}function Is(n,e,t){const r=e===void 0?t:e;if(typeof r!="boolean")throw dt(n,r,"a boolean");return r}function Yl(n,e){const t=n===void 0?e:n;if(t!==2&&t!==3)throw dt("dim",t,"2 or 3");return t}function Xl(n,e){if(n===void 0)return e;const t="an array of 2 or 3 finite numbers",r=n;if(typeof r!="object"||r===null||!("length"in r))throw dt("center",n,t);const{length:o}=r;if(o!==2&&o!==3)throw dt("center",n,t);const s=n[0],i=n[1],a=o===3?n[2]:0;if(typeof s!="number"||typeof i!="number"||typeof a!="number"||!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(a))throw dt("center",n,t);return[s,i,a]}function Ql(n,e){if(n===void 0)return e;const t=n;if(t!==null&&(typeof t!="number"||!Number.isFinite(t)))throw dt("seed",n,"a finite number or null");return t}function St(n){return Number.isInteger(n)&&n>=1}function aO(n){return n===null?0:Math.floor(Math.abs(n))%iO}function Ue(n,e){const t=n[e];if(typeof t!="number")throw dt(e,t,"a scalar field");return t}function cO(n,e){const t=n[e];if(typeof t=="number")throw dt(e,t,"a vector field");return t}function Ye(n,e){const t={};for(const r of Object.keys(e))t[r]=r in n?n[r]:e[r];return t}function Cm(n,e,t,r,o,s){const i=Math.max(1,Math.ceil(Math.ceil(o/n.workgroupSize)/Nw));for(let a=1;a<=i;a++)n.dispatch(e,t,{...r,z:a},[s])}class ks{constructor(e,t,r,o){this.boundRepulsion=null,this.boundSpeedFinalize=null,this.repulsion=e,this.speedFinalize=t,this.caps=r,this.overrides=Object.freeze({SWING_MODE:o.SWING_MODE,STRONG_GRAVITY:o.STRONG_GRAVITY,GRAVITY_CENTER:o.GRAVITY_CENTER}),this.finalizePlan=se(t.workgroupSize,t.workgroupSize,r)}static async create(e,t,r){const[o,s]=ks.specs(r),i=await e.kernel(o),a=await e.kernel(s);return new ks(i,a,t,r)}static specs(e){return[z("fa2-repulsion-exact",{SWING_MODE:e.SWING_MODE,STRONG_GRAVITY:e.STRONG_GRAVITY,GRAVITY_CENTER:e.GRAVITY_CENTER}),z("fa2-speed-finalize",{SWING_MODE:e.SWING_MODE})]}bind(e){this.boundRepulsion=this.repulsion.bind({pos:e.pos,S:e.state,force:e.force,oldForce:e.oldForce,fixedMask:e.fixedMask,partials:e.partials,P:e.params}),this.boundSpeedFinalize=this.speedFinalize.bind({partials:e.partials,S:e.state,T:e.trace,P:e.params})}record(e,t,r){this.recordRepulsion(e,t,r),this.recordSpeedFinalize(e,r)}recordRepulsion(e,t,r){const o=this.bound(this.boundRepulsion,"recordRepulsion"),s=se(t,this.repulsion.workgroupSize,this.caps);Cm(this.repulsion,e,o,s,t,r)}recordSpeedFinalize(e,t){const r=this.bound(this.boundSpeedFinalize,"recordSpeedFinalize");this.speedFinalize.dispatch(e,r,this.finalizePlan,[t])}bound(e,t){if(e===null)throw new S("E_NOT_LOADED",`RepulsionExact.${t}(): bind() has not been called for this stage`,{state:"unbound"});return e}}async function lO(n,e){const t=await n.pipelines.kernel(z("grid-centroid")),r=await n.pipelines.kernel(z("grid-centroid-hub")),o=await n.pipelines.kernel(z("grid-downsample"));return new uO(n,e,{centroid:t,hub:r,downsample:o})}class uO{constructor(e,t,r){this.bound=null,this.dispatches=0,this.scope=e,this.spec=t,this.kernels=r}get lastDispatches(){return this.dispatches}bind(e){const{centroid:t,hub:r,downsample:o}=this.kernels,{spec:s,scope:i}=this,a=e,c=[];let l=s.g;for(let u=0;u+1<s.levels;u++){l/=2;const d=l**s.dim,f=i.params(mp,{childBase:s.levelOffsets[u],parentBase:s.levelOffsets[u+1],parentSide:l,parentCells:d,depth:s.dim===3?2:1,pad0:0,pad1:0,pad2:0});c.push({bound:o.bind({pyramid:a.pyramid,P:f.binding}),offset:f.offset,parentCells:d})}this.bound={centroid:t.bind({sortedIdx:a.sortedIdx,cellStart:a.cellStart,pos:a.pos,pyramid:a.pyramid,hubList:a.hubList,hubCounters:a.hubCounters,P:a.params}),hub:r.bind({sortedIdx:a.sortedIdx,cellStart:a.cellStart,pos:a.pos,pyramid:a.pyramid,hubList:a.hubList,hubCount:a.hubCounters,P:a.params}),hubSlots:Math.floor(a.hubList.size/4),levels:c}}record(e,t,r){const{bound:o,scope:s,spec:i}=this;if(o===null)throw new S("E_NOT_LOADED","gridPyramid: record() before bind()",{argument:"bind"});const{centroid:a,hub:c,downsample:l}=this.kernels,u=i.cells+i.outsideCells;if(a.dispatch(e,o.centroid,se(u,s.workgroupSize,s.caps),[t]),c.dispatch(e,o.hub,mo(o.hubSlots,s.caps),[t]),this.dispatches=2,(r??"G5")!=="G4")for(const d of o.levels)l.dispatch(e,d.bound,se(d.parentCells,s.workgroupSize,s.caps),[d.offset]),this.dispatches+=1}}const dO=["G1","G2","G3","G4","G5","G6","G7"],cr=Se.STORAGE|Se.COPY_SRC|Se.COPY_DST;function qi(n){if(n.lease===null)throw new S("E_DISPOSED","RepulsionGrid: the stage was disposed",{label:"RepulsionGrid"});return n.lease}function fO(n,e,t,r){const o=e.uniform(t.byteLength,`grid/${t.name}`),s=new ArrayBuffer(t.byteLength);return t.write(new DataView(s),r),n.queue.writeBuffer(o,0,s),{binding:{buffer:o,offset:0,size:t.byteLength,window:null},offset:0}}function Nm(n){return z("grid-far-field",{LAW:n.LAW})}function Tm(n){return z("grid-near-field",{SWING_MODE:n.SWING_MODE,STRONG_GRAVITY:n.STRONG_GRAVITY,GRAVITY_CENTER:n.GRAVITY_CENTER,LAW:n.LAW})}class Fn{constructor(e,t,r,o,s,i,a){this.bound=null,this.caps=e.caps,this.box=s,this.workgroupSize=t,this.overrides=Object.freeze({SWING_MODE:r.SWING_MODE,STRONG_GRAVITY:r.STRONG_GRAVITY,GRAVITY_CENTER:r.GRAVITY_CENTER,LAW:r.LAW}),this.spec=o,this.build=i.build,this.pyramid=i.pyramid,this.far=a.far,this.near=a.near,this.speedFinalize=a.speedFinalize}static buffers(e,t){const r=4*Math.max(1,e);return[{name:"cellKey",byteLength:r,usage:cr,zero:!1},{name:"cellVal",byteLength:r,usage:cr,zero:!1},{name:"sortedKey",byteLength:r,usage:cr,zero:!1},{name:"sortedIdx",byteLength:r,usage:cr,zero:!1},{name:"cellHist",byteLength:4*t.histWords,usage:cr,zero:!0},{name:"cellStart",byteLength:4*t.histWords,usage:cr,zero:!0},{name:"hubList",byteLength:4*Math.max(1,Math.ceil(e/Dw)),usage:cr,zero:!1},{name:"pyramid",byteLength:zT(t),usage:cr,zero:!0}]}static specs(e,t){const r=t.deterministic?[z("radix-hist"),z("radix-scatter"),z("scan-block"),z("scan-add")]:[z("counting-scatter"),z("scan-block"),z("scan-add")];return[z("grid-cell-key"),...r,z("histogram"),z("fill"),z("grid-centroid"),z("grid-centroid-hub"),z("grid-downsample"),Nm(e),Tm(e),z("fa2-speed-finalize",{SWING_MODE:e.SWING_MODE})]}static async create(e,t,r,o){const s={lease:e.pool.lease()},i={device:e.device,caps:e.caps,pipelines:e.pipelines,pool:e.pool,workgroupSize:t,scratch:(a,c)=>qi(s).storage(a,c),params:(a,c)=>fO(e.device,qi(s),a,c)};try{const a=await GT(i,o),c=await lO(i,o),l=await e.pipelines.kernel(Nm(r)),u=await e.pipelines.kernel(Tm(r)),d=await e.pipelines.kernel(z("fa2-speed-finalize",{SWING_MODE:r.SWING_MODE}));return new Fn(e,t,r,o,s,{build:a,pyramid:c},{far:l,near:u,speedFinalize:d})}catch(a){throw qi(s).release(),a}}bind(e){qi(this.box);const t=e;this.build.bind({pos:t.pos,state:t.state,params:t.params,cellKey:t.cellKey,cellVal:t.cellVal,sortedKey:t.sortedKey,sortedIdx:t.sortedIdx,cellHist:t.cellHist,cellStart:t.cellStart}),this.pyramid.bind({pos:t.pos,params:t.params,sortedIdx:t.sortedIdx,cellStart:t.cellStart,pyramid:t.pyramid,hubList:t.hubList,hubCounters:t.hubCounters}),this.bound={far:this.far.bind({pos:t.pos,sortedIdx:t.sortedIdx,pyramid:t.pyramid,S:t.state,force:t.force,P:t.params}),near:this.near.bind({pos:t.pos,sortedIdx:t.sortedIdx,cellStart:t.cellStart,S:t.state,force:t.force,oldForce:t.oldForce,fixedMask:t.fixedMask,partials:t.partials,P:t.params}),speedFinalize:this.speedFinalize.bind({partials:t.partials,S:t.state,T:t.trace,P:t.params})}}recordRepulsion(e,t,r,o){const s=this.requireBound("recordRepulsion"),i=dO.indexOf(o??"G7");let a="G3";if(i===0?a="G1":i===1&&(a="G2"),this.build.record(e,t,r,a),i<3||(this.pyramid.record(e,r,i===3?"G4":"G5"),i<5))return;const c=se(t,this.workgroupSize,this.caps);this.far.dispatch(e,s.far,c,[r]),!(i<6)&&this.near.dispatch(e,s.near,c,[r])}recordSpeedFinalize(e,t){const r=this.requireBound("recordSpeedFinalize"),o=se(this.speedFinalize.workgroupSize,this.speedFinalize.workgroupSize,this.caps);this.speedFinalize.dispatch(e,r.speedFinalize,o,[t])}dispose(){this.box.lease!==null&&(this.box.lease.release(),this.box.lease=null);for(const e of[this.far,this.near,this.speedFinalize])e.invalidate();this.bound=null}requireBound(e){if(this.bound===null)throw new S("E_NOT_LOADED",`RepulsionGrid.${e}(): bind() has not been called for this stage`,{state:"unbound"});return this.bound}}const Ss=["K1","K2","K3","G1","G2","G3","G4","G5","G6","G7","K4","K5","toScene"],hO=3,Jl=10,Om=11,Zl=12,$m="hubCounters",gO={x:1,y:1,z:1,items:1,stride:null},Hi={STATS_MODE:0},Ki={LINLOG:!1,DISTRIBUTED:!1,TIER:0,USE_PERM:!1,HAS_WEIGHTS:!1,LAW:0},Yi={SWING_MODE:0,STRONG_GRAVITY:!1,GRAVITY_CENTER:0,LAW:0},Xi={SWING_MODE:0,APPLY:0};class Qi{constructor(e,t,r){this.kernel=e,this.bound=t,this.plan=r}static binder(e){return({pos:t,state:r,force:o,oldForce:s,fixedMask:i,partials:a,params:c},l)=>new Qi(e,e.bind({pos:t,S:r,force:o,oldForce:s,fixedMask:i,partials:a,P:c}),l)}recordRepulsion(e,t,r){Cm(this.kernel,e,this.bound,this.plan,t,r)}invalidate(){this.kernel.invalidate()}}class eu{constructor(e,t){this.names=t,this.stages=Ss,this.params=Dt,this.state=nn,this.trace=yo,this.resources=null,this.nextGrid=null,this.resetCarry=!1,this.bound=null,this.openPass=null,this.tuning=e}zeroesCarry(){return!1}recordSpeed(e,t,r){}buffers(e,t){const r=Math.max(1,e)*sO,o=Se.STORAGE|Se.COPY_SRC|Se.COPY_DST,s=Es(this.tuning,e)==="grid"?Fn.buffers(e,Un(e,t,this.tuning)):[];return[{name:"force",byteLength:r,usage:o,zero:!0},{name:this.names.carry,byteLength:r,usage:o,zero:!0},{name:xm,byteLength:Vt,usage:Se.UNIFORM|Se.COPY_DST,zero:!1},{name:$m,byteLength:16,usage:o,zero:!0},...s]}async bind(e,t){this.dropBound(),this.resources=e;const{n:r,caps:o,core:s,ring:i,device:a}=e;if(r===0)return;const c=e.buffer("positions"),l=e.buffer("force"),u=i.binding(Dt),d=s.colIdx!==null,f=await this.compile(e,t),{k1:h,k5:g,toScene:w,fill:p,grid:m}=f;if(this.resources!==e){m?.dispose();return}const y=e.buffer("scenePositions"),b=e.buffer("fixed"),v=e.buffer("partials"),A=e.buffer("state"),E=e.buffer("trace"),I=e.buffer(this.names.carry),k=e.buffer(xm),N={buffer:k.buffer,offset:k.offset,size:Ze.byteLength,window:null},C=new ArrayBuffer(Ze.byteLength);Ze.write(new DataView(C),{count:3*r,value:0,mode:0}),a.queue.writeBuffer(k.buffer,k.offset,C);const O=e.buffer($m),T={pos:c,state:A,trace:E,force:l,oldForce:I,fixedMask:b,partials:v,params:u};m?.bind({...T,cellKey:e.buffer("cellKey"),cellVal:e.buffer("cellVal"),sortedKey:e.buffer("sortedKey"),sortedIdx:e.buffer("sortedIdx"),cellHist:e.buffer("cellHist"),cellStart:e.buffer("cellStart"),hubList:e.buffer("hubList"),hubCounters:O,pyramid:e.buffer("pyramid")});const $=h.workgroupSize,L=se(r,$,o);this.bound={n:r,plan:L,fillPlan:se(3*r,$,o),k1:h,k1Bound:h.bind({partials:v,S:A,T:E,cellHist:m===null?v:e.buffer("cellHist"),hubCounters:O,P:u}),attraction:f.attraction===null?null:rO(f.attraction,e,{pos:c,force:l,params:u}),exact:f.exact?.(T,L)??null,grid:m,k5:g,k5Bound:g.bind({force:l,oldForce:I,fixedMask:b,S:A,pos:c,partials:v,P:u}),toScene:w,toSceneBound:w.bind({pos:c,scene:y,P:u}),fill:p,fillForceBound:d?null:p.bind({dst:l,P:N}),fillCarryBound:this.zeroesCarry()?p.bind({dst:I,P:N}):null}}recordIteration(e,t,r,o){const s=this.requireResources(),i=o===void 0?Zl:this.stageIndex(o),{bound:a}=this;if(a===null){if(s.n===0)return;throw new S("E_NOT_LOADED",`the ${this.names.name} model is not bound (bind() has not completed)`,{state:"loaded"})}const c=s.ring.offsetOf(t);if(r==="grid"){this.recordGridIteration(e,a,c,i);return}const{exact:l}=a;if(l===null)throw new S("E_NOT_LOADED",`the ${this.names.name} model was bound on the grid tier`,{state:"loaded"});const u=this.openPass!==null&&this.openPass.id===e.id?this.openPass.pass:e.pass(this.names.pass);this.openPass={id:e.id,pass:u},this.recordK1(u,a,c),!(i<1)&&(this.recordK2(u,a,c),!(i<2)&&(l.recordRepulsion(u,a.n,c),!(i<Jl)&&(this.recordSpeed(u,l,c),!(i<Om)&&(a.k5.dispatch(u,a.k5Bound,a.plan,[c]),!(i<Zl)&&this.recordToScene(e,a,c)))))}recordGridIteration(e,t,r,o){const{grid:s}=t;if(s===null)throw new S("E_NOT_LOADED",`the ${this.names.name} model was bound on the exact tier`,{state:"loaded"});if(this.openPass=null,this.recordK1(e.pass(`${this.names.pass}-k1`),t,r),o<1||(this.recordK2(e.pass(`${this.names.pass}-attraction`),t,r),o<hO))return;const i=e.pass(`${this.names.pass}-grid`),a=o<Jl?Ss[o]:void 0;s.recordRepulsion(i,t.n,r,a),!(o<Jl)&&(this.recordSpeed(i,s,r),!(o<Om)&&(t.k5.dispatch(i,t.k5Bound,t.plan,[r]),!(o<Zl)&&this.recordToScene(e,t,r)))}recordK1(e,t,r){this.resetCarry&&(this.resetCarry=!1,t.fillCarryBound!==null&&t.fill.dispatch(e,t.fillCarryBound,t.fillPlan,[0])),t.k1.dispatch(e,t.k1Bound,gO,[r])}recordK2(e,t,r){t.attraction!==null?oO(e,t.attraction,r):t.fillForceBound!==null&&t.fill.dispatch(e,t.fillForceBound,t.fillPlan,[0])}recordToScene(e,t,r){this.openPass=null;const o=e.pass(this.names.scenePass);t.toScene.dispatch(o,t.toSceneBound,t.plan,[r])}sharedParams(e,t){const{n:r,core:o,tiers:s,tier:i,dim:a}=this.requireResources(),{nearMax:c,extentFactor:l}=this.tuning,u=i==="grid"?Un(r,a,this.tuning):null,d=s?.segmentOffsets,f=d?.[1]??0,h=d?.[2]??0;return{n:r,dim:t.dim,flags:0,tierStart:h,tierEnd:r,iterationIndex:e,seed:aO(t.seed),nearMax:c,scale:t.scale,center:[t.center[0],t.center[1],t.center[2],0],settleThreshold:t.settleThreshold,extentFactor:l,gridMax:u?.g??0,levels:u?.levels??0,arcBase:0,arcEnd:Li(o),accumulate:0,hiEnd:f,midEnd:h}}sharedStats(e){const t=cO(e,"centroid"),r=this.resources?.tier==="grid";return{iteration:Ue(e,"iteration"),meanDisplacement:Ue(e,"meanDisplacement"),rmsRadius:Ue(e,"rmsRadius"),layoutRadius:Ue(e,"radius"),centroid:[t[0],t[1],t[2]],repulsionTier:r?"grid":"exact",maxCellOccupancy:r?Ue(e,"maxCellOccupancy"):null,outsideGrid:r?Ue(e,"outsideGrid"):null,msPerIteration:null}}requireResources(){if(this.resources===null)throw new S("E_NOT_LOADED",`the ${this.names.name} model has not been bound (load() first)`,{state:"created"});return this.resources}stageIndex(e){for(let t=0;t<Ss.length;t++)if(Ss[t]===e)return t;throw dt("upTo",e,Ss.join(" | "))}dispose(){this.dropBound()}dropBound(){this.openPass=null;const{bound:e}=this;if(e!==null){for(const t of[e.k1,e.k5,e.toScene,e.fill])t.invalidate();e.exact?.invalidate?.();for(const[t]of e.attraction?.kernels??[])t.invalidate();e.grid?.dispose(),this.bound=null}}}const Rm="write a role 'mass' node column (nodes.set(name, vec, { role: 'mass', replaceRole: true })) or pass a Float32Array; @graphty/layout's resolveNodeVector does this on the CPU path";function En(n,e,t,r){return new S("E_INVALID_ARGUMENT",r,{argument:n,value:e,expected:t})}function tu(n,e){for(let t=0;t<n.length;t++){const r=n[t];if(!Number.isFinite(r)||r<=0)throw new S("E_INVALID_ARGUMENT",`${e}: mass[${t}] = ${r} is not a finite number > 0`,{argument:"nodeMass",value:r,index:t,expected:"finite masses > 0"})}}function wO(n){const e=n.nodeCount,t=n.outDegree(),r=new Float32Array(e);for(let o=0;o<e;o++)r[o]=t[o]+1;return r}function Dm(n,e){const{name:t}=e.meta;if(e.meta.components!==1)throw En("nodeMass",t,"a one-component numeric node column",`node column "${t}" has ${e.meta.components} components; a mass column has one`);let r;switch(e.dtype){case"f32":case"f64":{const s=n.nodes.gpuView(t),i=s instanceof Float32Array?s:new Float32Array(s);return tu(i,`node column "${t}"`),i}case"u32":case"i32":r=n.nodes.gpuView(t);break;case"u8":r=e.data;break;default:throw En("nodeMass",t,"a numeric node column (f32, f64, u32, i32, u8)",`node column "${t}" is ${e.dtype}, not numeric`)}const o=new Float32Array(n.nodeCount);for(let s=0;s<o.length;s++)o[s]=r[s];return tu(o,`node column "${t}"`),o}function pO(n,e){const t=n.nodeCount;if(e==null){const r=n.nodes.byRole("mass");return r===null?wO(n):Dm(n,r)}if(e instanceof Float32Array){if(e.length!==t)throw En("nodeMass",e.length,`${t} values`,`nodeMass has ${e.length} values, expected ${t}`);return tu(e,"nodeMass"),e}if(typeof e=="string"){const r=n.nodes.get(e);if(r===null)throw En("nodeMass",e,"an existing numeric node column",`nodeMass names node column "${e}", which the snapshot does not hold`);return Dm(n,r)}throw ArrayBuffer.isView(e)?En("nodeMass","typed array","a Float32Array","nodeMass must be a Float32Array, a column name or null"):new S("E_UNSUPPORTED",`nodeMass as a Record is not supported on the GPU path: ${Rm}`,{option:"nodeMass",hint:Rm})}function mO(n,e){if(e===!0)return{data:n.weights,source:"arcs",column:null};if(e===!1||e===null||e===void 0)return{data:null,source:"none",column:null};if(typeof e!="string")throw En("weight",e,"true, false, null or an edge column name","weight must be true, false, null or an edge column name");const t=n.edges.get(e);if(t===null)throw En("weight",e,"an existing numeric edge column",`weight names edge column "${e}", which the snapshot does not hold`);if(t.meta.components!==1)throw En("weight",e,"a one-component numeric edge column",`edge column "${e}" has ${t.meta.components} components; a weight column has one`);switch(t.dtype){case"f32":case"f64":case"u32":case"i32":{const r=n.edges.gpuView(e),o=Va(n,r);return{data:o instanceof Float32Array?o:new Float32Array(o),source:"column",column:t}}case"string":case"list":case"json":throw n.edges.gpuView(e),En("weight",e,"a numeric edge column",`edge column "${e}" is ${t.dtype}`);default:throw En("weight",e,"an f32 / f64 / u32 / i32 edge column",`edge column "${e}" is ${t.dtype}: its gpuView is packed words, not per-edge values`)}}const Lm={LINLOG:!1,DISTRIBUTED:!1,TIER:0,USE_PERM:!1,HAS_WEIGHTS:!1},Mm={SWING_MODE:0},yO=Object.freeze({...Cr,nodeMass:null,nodeSize:null,weight:null,center:[0,0,0],seed:null});function nu(n){return{SWING_MODE:n.SWING_MODE===1?1:0,STRONG_GRAVITY:n.STRONG_GRAVITY===!0,GRAVITY_CENTER:n.GRAVITY_CENTER===1?1:0}}function Um(n){return{...nu(n),LAW:0}}function Rr(n,e){const t=n??{},r=e??yO;if(e!==void 0&&t.maxInFlight!==void 0&&t.maxInFlight!==e.maxInFlight)throw new S("E_INVALID_ARGUMENT",`maxInFlight cannot change after creation (the uniform ring is sized by it): got ${ji(t.maxInFlight)}, current ${e.maxInFlight}`,{argument:"maxInFlight",value:t.maxInFlight,expected:e.maxInFlight});const o=t.nodeSize===void 0?r.nodeSize:t.nodeSize;if(o!==null)throw new S("E_UNSUPPORTED","nodeSize (the adjustSizes correction) is not supported by the GPU ForceAtlas2 yet (spec 7.14)",{option:"nodeSize",hint:"pass nodeSize: null; the size-aware repulsion is deferred (spec 7.2, Q-25)"});const s={maxIter:ke("maxIter",t.maxIter,r.maxIter,St,"an integer >= 1"),jitterTolerance:ke("jitterTolerance",t.jitterTolerance,r.jitterTolerance,i=>i>0,"> 0"),scalingRatio:ke("scalingRatio",t.scalingRatio,r.scalingRatio,i=>i>0,"> 0"),gravity:ke("gravity",t.gravity,r.gravity,i=>i>=0,">= 0"),strongGravity:Is("strongGravity",t.strongGravity,r.strongGravity),distributedAction:Is("distributedAction",t.distributedAction,r.distributedAction),linlog:Is("linlog",t.linlog,r.linlog),nodeMass:t.nodeMass===void 0?r.nodeMass:t.nodeMass,nodeSize:o,weight:t.weight===void 0?r.weight:t.weight,dissuadeHubs:Is("dissuadeHubs",t.dissuadeHubs,r.dissuadeHubs),dim:Yl(t.dim,r.dim),scale:ke("scale",t.scale,r.scale,i=>i>0,"> 0"),center:Xl(t.center,r.center),seed:Ql(t.seed,r.seed),settleThreshold:ke("settleThreshold",t.settleThreshold,r.settleThreshold,i=>i>=0,">= 0"),settleWindow:ke("settleWindow",t.settleWindow,r.settleWindow,St,"an integer >= 1"),iterationsPerStep:ke("iterationsPerStep",t.iterationsPerStep,r.iterationsPerStep,i=>St(i)&&i<=Rt,`an integer in [1, ${Rt}]`),maxInFlight:ke("maxInFlight",t.maxInFlight,r.maxInFlight,St,"an integer >= 1")};return Object.freeze(s)}function ru(n){const e=n??{},t=e.repulsion??nr.repulsion;if(t!=="exact"&&t!=="grid"&&t!=="auto")throw dt("repulsion",t,'"exact", "grid" or "auto"');const r=e.compat??nr.compat;if(r!=="paper"&&r!=="networkx")throw dt("compat",r,'"paper" or "networkx"');const o={repulsion:t,exactMaxNodes:ke("exactMaxNodes",e.exactMaxNodes,nr.exactMaxNodes,St,"an integer >= 1"),nearMax:ke("nearMax",e.nearMax,nr.nearMax,s=>St(s)&&s>=2,"an integer >= 2"),deterministic:Is("deterministic",e.deterministic,nr.deterministic),gridMax2D:ke("gridMax2D",e.gridMax2D,nr.gridMax2D,St,"an integer >= 1"),gridMax3D:ke("gridMax3D",e.gridMax3D,nr.gridMax3D,St,"an integer >= 1"),extentFactor:ke("extentFactor",e.extentFactor,nr.extentFactor,s=>s>0,"> 0"),compat:r};return Object.freeze(o)}class bO extends eu{constructor(e,t){super(e,{name:"ForceAtlas2",pass:"fa2",scenePass:"fa2-to-scene",carry:"oldForce"}),this.kind="forceatlas2",this.current=t}get swingMode(){return this.tuning.compat==="networkx"?1:0}inputs(e,t){const r=Rr(t,this.current),o=e.nodeCount,s={mass:pO(e,r.nodeMass),weights:mO(e,r.weight)};return this.nextGrid=Es(this.tuning,o)==="grid"?Un(o,r.dim,this.tuning):null,s}overrides(e){const t=Rr(e,this.current),r=this.swingMode;return{LINLOG:t.linlog,DISTRIBUTED:t.distributedAction,TIER:0,SWING_MODE:r,STRONG_GRAVITY:t.strongGravity,GRAVITY_CENTER:r}}specs(e,t){const[r,o]=ks.specs(nu(e)),s=this.nextGrid===null?[]:Fn.specs(Um(e),Un(kw+1,2,this.tuning));return[z("fa2-stats-finalize"),z("fa2-attraction",Ye(e,Lm)),r,o,z("fa2-integrate",Ye(e,Mm)),z("fa2-to-scene"),z("fill"),...s]}async compile(e,t){const{n:r,pipelines:o,caps:s}=e,[i,a,c,l]=await Promise.all([o.kernel(z("fa2-stats-finalize")),o.kernel(z("fa2-integrate",Ye(t,Mm))),o.kernel(z("fa2-to-scene")),o.kernel(z("fill"))]),u=e.tier==="grid"?null:await ks.create(o,s,nu(t)),d=e.core.colIdx!==null?await Kl(e,Ye(t,Lm)):null,f=e.tier==="grid"?await Fn.create(e,i.workgroupSize,Um(t),Un(r,e.dim,this.tuning)):null;return{k1:i,k5:a,toScene:c,fill:l,attraction:d,exact:u===null?null:g=>(u.bind(g),u),grid:f}}zeroesCarry(){return this.swingMode===0}recordSpeed(e,t,r){t.recordSpeedFinalize(e,r)}paramsFor(e,t){this.requireResources();const r=Rr(t,this.current);return{...this.sharedParams(e,r),scalingRatio:r.scalingRatio,gravity:r.gravity,jitterTolerance:r.jitterTolerance,settleFloor:Ok}}onLoad(e){e.set("speed",1),e.set("speedEfficiency",1),e.set("swing",1),e.set("traction",1),this.resetCarry=!0,this.nextGrid!==null&&ou(e,this.nextGrid,this.tuning.extentFactor)}onReheat(e){this.swingMode===1&&(e.set("swing",1),e.set("traction",1))}onSetParams(e,t){const r=Rr(e,this.current),o=r.linlog!==this.current.linlog||r.strongGravity!==this.current.strongGravity||r.distributedAction!==this.current.distributedAction;this.current=r,o&&(t.set("speed",1),t.set("speedEfficiency",1))}readStats(e,t){const r=nn.read(e),o=[],s=Math.floor(t.byteLength/fo);for(let i=0;i<s;i++){const a=yo.read(t,i*fo);o.push({swing:Ue(a,"swing"),traction:Ue(a,"traction"),speed:Ue(a,"speed"),speedEfficiency:Ue(a,"speedEfficiency"),meanDisplacement:Ue(a,"meanDisplacement"),settledCount:Ue(a,"settledCount")})}return{...this.sharedStats(r),swing:Ue(r,"swing"),traction:Ue(r,"traction"),speed:Ue(r,"speed"),speedEfficiency:Ue(r,"speedEfficiency"),trace:o}}}function ou(n,e,t){const r=Math.fround,o=w=>{const p=n.get(w);return typeof p=="number"?[p,p,p]:p},s=o("min"),i=o("max"),a=o("centroid"),c=n.get("rmsRadius"),l=[0,1,2].map(w=>r(r(r(i[w])-r(s[w]))*r(Mw))),u=e.dim===3?Math.max(l[0],l[1],l[2]):Math.max(l[0],l[1]),d=r(r(t)*r(typeof c=="number"?c:0)),f=Math.max(Math.min(u,d),r(Lw)),h=r(f/e.g),g=r(.5*f);n.set("gridMin",[r(r(a[0])-g),r(r(a[1])-g),r(r(a[2])-g),h]),n.set("invCellSize",r(1/h)),n.set("eps",r(.25*h)),n.set("outsideGrid",0),n.set("maxCellOccupancy",0)}function vO(n,e){return Rr(n,Rr(e))}function AO(n,e){n.assertReady();const t=Rr(e),r=ru(e),o=new bO(r,t);return new Hl(n,o,t,r,vO)}const EO=Object.freeze({LINLOG:!1,DISTRIBUTED:!1,TIER:0,SWING_MODE:1,STRONG_GRAVITY:!1,GRAVITY_CENTER:0,LAW:1,APPLY:1,STATS_MODE:1}),Fm=Object.freeze({SWING_MODE:1,STRONG_GRAVITY:!1,GRAVITY_CENTER:0,LAW:1}),_O=Object.freeze({...Ck,center:[0,0,0],seed:null});function IO(n,e){return n===void 0?e:n===null||n===0||Number.isNaN(n)?null:ke("k",n,1,t=>t>0,"> 0 or null")}function kO(n,e){if(n===void 0)return e;if(n==="linear"||n==="adaptive")return n;throw dt("cooling",n,'"linear" | "adaptive"')}function Co(n,e){const t=n??{},r=e??_O;if(e!==void 0&&t.maxInFlight!==void 0&&t.maxInFlight!==e.maxInFlight)throw new S("E_INVALID_ARGUMENT",`maxInFlight cannot change after creation (the uniform ring is sized by it): got ${ji(t.maxInFlight)}, current ${e.maxInFlight}`,{argument:"maxInFlight",value:t.maxInFlight,expected:e.maxInFlight});const o=t.fixed===void 0?r.fixed:t.fixed;if(o!==null&&typeof o!="string"&&!(o instanceof Uint32Array))throw dt("fixed",o,"a NodeMask (Uint32Array), the name of a bool node column, or null");const s=kO(t.cooling,r.cooling),i=e===void 0&&s==="adaptive"&&t.iterations===void 0?xk:r.iterations,a={k:IO(t.k,r.k),iterations:ke("iterations",t.iterations,i,c=>Number.isInteger(c)&&c>=0,"an integer >= 0"),cooling:s,fixed:o,dim:Yl(t.dim,r.dim),scale:ke("scale",t.scale,r.scale,c=>c>0,"> 0"),center:Xl(t.center,r.center),seed:Ql(t.seed,r.seed),settleThreshold:ke("settleThreshold",t.settleThreshold,r.settleThreshold,c=>c>=0,">= 0"),settleWindow:ke("settleWindow",t.settleWindow,r.settleWindow,St,"an integer >= 1"),iterationsPerStep:ke("iterationsPerStep",t.iterationsPerStep,r.iterationsPerStep,c=>St(c)&&c<=Rt,`an integer in [1, ${Rt}]`),maxInFlight:ke("maxInFlight",t.maxInFlight,r.maxInFlight,St,"an integer >= 1")};return Object.freeze(a)}function SO(n,e){const t=Math.ceil(n.nodeCount/32);if(typeof e=="string"){const o=n.nodes.get(e);if(o===null)throw dt("fixed",e,`the name of a bool node column (the snapshot holds no node column "${e}")`);if(o.dtype!=="bool")throw dt("fixed",e,`the name of a bool node column ("${e}" is ${o.dtype})`);return new Uint32Array(o.data.subarray(0,t))}if(e!==null){if(e.length<t)throw dt("fixed",e.length,`a mask of at least ${t} words for ${n.nodeCount} nodes`);return new Uint32Array(e.subarray(0,t))}const r=n.nodes.byRole("fixed");return r!==null&&r.dtype==="bool"?new Uint32Array(r.data.subarray(0,t)):null}class PO extends eu{constructor(e,t){super(e,{name:"Fruchterman-Reingold",pass:"fr",scenePass:"fa2-to-scene",carry:"oldForce"}),this.kind="fruchtermanReingold",this.tempOrigin=0,this.pendingReheat=!1,this.current=t}inputs(e,t){const r=Co(t,this.current),o={mass:new Float32Array(e.nodeCount).fill(1),weights:{data:null,source:"none",column:null},fixed:SO(e,r.fixed)},s=e.nodeCount;return this.nextGrid=Es(this.tuning,s)==="grid"?Un(s,r.dim,this.tuning):null,o}overrides(e){return EO}specs(e,t){const r=this.nextGrid===null?[]:Fn.specs(Fm,this.nextGrid);return[z("fa2-stats-finalize",Ye(e,Hi)),z("fa2-attraction",Ye(e,Ki)),z("fa2-repulsion-exact",Ye(e,Yi)),z("fa2-integrate",Ye(e,Xi)),z("fa2-to-scene"),z("fill"),...r]}async compile(e,t){const{n:r,pipelines:o}=e,s=await o.kernel(z("fa2-stats-finalize",Ye(t,Hi))),i=e.core.colIdx!==null?await Kl(e,Ye(t,Ki)):null,a=e.tier==="grid"?null:await o.kernel(z("fa2-repulsion-exact",Ye(t,Yi))),c=await o.kernel(z("fa2-integrate",Ye(t,Xi))),l=await o.kernel(z("fa2-to-scene")),u=await o.kernel(z("fill")),d=e.tier==="grid"?await Fn.create(e,s.workgroupSize,Fm,Un(r,e.dim,this.tuning)):null,f=a===null?null:Qi.binder(a);return{k1:s,k5:c,toScene:l,fill:u,attraction:i,exact:f,grid:d}}paramsFor(e,t){const{n:r}=this.requireResources(),o=Co(t,this.current),s=o.cooling==="adaptive";return{...this.sharedParams(e,o),flags:s?Tw:0,scalingRatio:0,gravity:0,jitterTolerance:0,frK:o.k??1/Math.sqrt(r),settleFloor:Ow.fruchtermanReingold*(o.k??1/Math.sqrt(r)),temperature:s?Si:this.temperatureAt(e,o)}}onLoad(e){this.resetAdaptive(e),e.set("kineticEnergy",0),this.tempOrigin=0,this.pendingReheat=!1,this.nextGrid!==null&&ou(e,this.nextGrid,this.tuning.extentFactor)}resetAdaptive(e){e.set("temperature",Si),e.set("frEnergy",Number.POSITIVE_INFINITY),e.set("frProgress",0)}onReheat(e){this.pendingReheat=!0,this.current.cooling==="adaptive"&&this.resetAdaptive(e)}onSetParams(e,t){this.current=Co(e,this.current)}readStats(e,t){const r=nn.read(e),o=[],s=Math.floor(t.byteLength/fo);for(let i=0;i<s;i++){const a=yo.read(t,i*fo);o.push({temperature:Ue(a,"modelScalar"),meanDisplacement:Ue(a,"meanDisplacement"),settledCount:Ue(a,"settledCount")})}return{...this.sharedStats(r),temperature:Ue(r,"temperature"),trace:o}}temperatureAt(e,t){this.pendingReheat&&(this.tempOrigin=e-Math.floor(kk*t.iterations),this.pendingReheat=!1);const r=Si/(t.iterations+1);return Math.max(0,Si-r*(e-this.tempOrigin))}}function xO(n,e){if("fixed"in n)throw new S("E_INVALID_ARGUMENT","setParams({ fixed }) is not a live option (spec 7.12)",{argument:"fixed",value:n.fixed,expected:"absent",hint:"use setFixed(mask); fixed is applied at load()"});return Co(n,Co(e))}function CO(n,e){n.assertReady();const t=Co(e),r=ru(e),o=new PO(r,t);return new Hl(n,o,t,r,xO)}const NO=Object.freeze({LINLOG:!1,DISTRIBUTED:!1,TIER:0,SWING_MODE:1,STRONG_GRAVITY:!1,GRAVITY_CENTER:0,LAW:2,APPLY:2,STATS_MODE:2}),Bm=Object.freeze({SWING_MODE:1,STRONG_GRAVITY:!1,GRAVITY_CENTER:0,LAW:2}),TO="velocity",OO=Object.freeze({...sl,maxIter:null,gravity:null,springCoefficient:null,center:[0,0,0],seed:null});function zm(n){return Math.min(1,Nk/Math.max(1,n))}function su(n,e,t,r,o){return e===void 0?t:e===null?null:ke(n,e,1,r,`${o} or null`)}function No(n,e){const t=n??{},r=e??OO;if(e!==void 0&&t.maxInFlight!==void 0&&t.maxInFlight!==e.maxInFlight)throw new S("E_INVALID_ARGUMENT",`maxInFlight cannot change after creation (the uniform ring is sized by it): got ${ji(t.maxInFlight)}, current ${e.maxInFlight}`,{argument:"maxInFlight",value:t.maxInFlight,expected:e.maxInFlight});const o={maxIter:su("maxIter",t.maxIter,r.maxIter,St,"an integer >= 1"),springLength:ke("springLength",t.springLength,r.springLength,s=>s>0,"> 0"),springCoefficient:su("springCoefficient",t.springCoefficient,r.springCoefficient,s=>s>0,"> 0"),gravity:su("gravity",t.gravity,r.gravity,()=>!0,"a finite number (negative repels)"),dragCoefficient:ke("dragCoefficient",t.dragCoefficient,r.dragCoefficient,s=>s>=0,">= 0"),timeStep:ke("timeStep",t.timeStep,r.timeStep,s=>s>0,"> 0"),dim:Yl(t.dim,r.dim),scale:ke("scale",t.scale,r.scale,s=>s>0,"> 0"),center:Xl(t.center,r.center),seed:Ql(t.seed,r.seed),settleThreshold:ke("settleThreshold",t.settleThreshold,r.settleThreshold,s=>s>=0,">= 0"),settleWindow:ke("settleWindow",t.settleWindow,r.settleWindow,St,"an integer >= 1"),iterationsPerStep:ke("iterationsPerStep",t.iterationsPerStep,r.iterationsPerStep,s=>St(s)&&s<=Rt,`an integer in [1, ${Rt}]`),maxInFlight:ke("maxInFlight",t.maxInFlight,r.maxInFlight,St,"an integer >= 1")};return Object.freeze(o)}function $O(n){const e=n.outDegree(),t=new Float32Array(n.nodeCount);for(let r=0;r<n.nodeCount;r++)t[r]=1+e[r]/3;return t}class RO extends eu{constructor(e,t){super(e,{name:"spring-electrical",pass:"se",scenePass:"se-to-scene",carry:TO}),this.kind="springElectrical",this.current=t}inputs(e,t){const{dim:r}=No(t,this.current),o=e.nodeCount;return this.nextGrid=Es(this.tuning,o)==="grid"?Un(o,r,this.tuning):null,{mass:$O(e),weights:{data:null,source:"none",column:null}}}overrides(e){return NO}specs(e,t){const r=this.nextGrid===null?[]:Fn.specs(Bm,this.nextGrid);return[z("fa2-stats-finalize",Ye(e,Hi)),z("fa2-attraction",Ye(e,Ki)),z("fa2-repulsion-exact",Ye(e,Yi)),z("fa2-integrate",Ye(e,Xi)),z("fa2-to-scene"),z("fill"),...r]}async compile(e,t){const{n:r,pipelines:o}=e,[s,i,a,c]=await Promise.all([o.kernel(z("fa2-stats-finalize",Ye(t,Hi))),o.kernel(z("fa2-integrate",Ye(t,Xi))),o.kernel(z("fa2-to-scene")),o.kernel(z("fill"))]),l=e.core.colIdx!==null?await Kl(e,Ye(t,Ki)):null,u=e.tier==="grid"?null:await o.kernel(z("fa2-repulsion-exact",Ye(t,Yi))),d=e.tier==="grid"?await Fn.create(e,s.workgroupSize,Bm,Un(r,e.dim,this.tuning)):null,f=u===null?null:Qi.binder(u);return{k1:s,k5:i,toScene:a,fill:c,attraction:l,exact:f,grid:d}}paramsFor(e,t){const{n:r}=this.requireResources(),o=No(t,this.current);return{...this.sharedParams(e,o),scalingRatio:0,gravity:0,jitterTolerance:0,frK:0,temperature:0,springLength:o.springLength,settleFloor:Ow.springElectrical*o.springLength*(Tk/Math.max(r,1))**.25,springCoefficient:o.springCoefficient??sl.springCoefficient*zm(r),coulomb:o.gravity??sl.gravity*zm(r),dragCoefficient:o.dragCoefficient,timeStep:o.timeStep}}onLoad(e){e.set("kineticEnergy",0),e.set("temperature",0),this.nextGrid!==null&&ou(e,this.nextGrid,this.tuning.extentFactor)}onReheat(e){}onSetParams(e,t){this.current=No(e,this.current)}readStats(e,t){const r=nn.read(e),o=[],s=Math.floor(t.byteLength/fo);for(let i=0;i<s;i++){const a=yo.read(t,i*fo);o.push({kineticEnergy:Ue(a,"modelScalar"),meanDisplacement:Ue(a,"meanDisplacement"),settledCount:Ue(a,"settledCount")})}return{...this.sharedStats(r),kineticEnergy:Ue(r,"kineticEnergy"),trace:o}}}function DO(n,e){return No(n,No(e))}function LO(n,e){n.assertReady();const t=No(e),r=ru(e),o=new RO(r,t);return new Hl(n,o,t,r,DO)}function Gm(n,e,t){return n===void 0||e?.sources!==void 0||e?.k!==void 0?e:n.sources!==void 0?{...e,sources:n.sources.filter(r=>r<t)}:{...e,k:n.k!==void 0&&n.k<t?n.k:void 0}}function MO(n){return Object.freeze({})}function UO(n,e){n.assertReady();const t=MO();return{kind:"webgpu",harmonicCloseness:!0,ctx:n,options:t,forceAtlas2(r){return n.assertReady(),AO(n,{...r,...t.layout})},fruchtermanReingold(r){return n.assertReady(),CO(n,{...r,...t.layout})},springElectrical(r){return n.assertReady(),LO(n,{...r,...t.layout})},async pageRank(r,o){return n.assertReady(),await CT(n,r,o)},async personalizedPageRank(r,o,s){n.assertReady();const i=o instanceof Float32Array?o:Float32Array.from(o);return await NT(n,r,i,s)},async hits(r,o){return n.assertReady(),await $T(n,r,o)},async eigenvectorCentrality(r,o){return n.assertReady(),await TT(n,r,o)},async katzCentrality(r,o){return n.assertReady(),await OT(n,r,o)},async connectedComponents(r,o){return n.assertReady(),await nm(n,r,o)},async weaklyConnectedComponents(r,o){return n.assertReady(),await nm(n,r,o)},async breadthFirstSearch(r,o,s){return n.assertReady(),await aN(n,r,o,s)},async sssp(r,o,s){return n.assertReady(),await Gp(n,r,o,s)},async bellmanFord(r,o,s){return n.assertReady(),await mN(n,r,o,s)},async betweennessCentrality(r,o){return n.assertReady(),await PN(n,r,Gm(t.algorithms?.betweenness,o,r.nodeCount))},async edgeBetweennessCentrality(r,o){return n.assertReady(),await xN(n,r,Gm(t.algorithms?.betweenness,o,r.nodeCount))},async closenessCentrality(r,o){return n.assertReady(),await MN(n,r,o)},async allPairsShortestPath(r,o){n.assertReady();for(const s of["cutoff","weights"])if(o?.[s]!==void 0)throw new S("E_UNSUPPORTED",`allPairsShortestPath: ${s} is not supported`,{option:s,hint:"all-pairs shortest paths runs over the snapshot's own weights with no cutoff"});return await dN(n,r)},async triangleCount(r){return n.assertReady(),await LT(n,r)},async labelPropagation(r,o){if(n.assertReady(),o?.tolerance!==void 0)throw new S("E_UNSUPPORTED","labelPropagation: tolerance has no meaning here",{option:"tolerance",hint:"label propagation stops at a fixed point or after maxIterations passes"});return await vT(n,r,{maxIterations:o?.maxIterations,weighted:o?.weighted})},async minimumSpanningTree(r,o){if(n.assertReady(),o?.weights!==void 0)throw new S("E_UNSUPPORTED","minimumSpanningTree: weights is not supported",{option:"weights",hint:"the spanning forest runs over the snapshot's own edge weights"});return await kT(n,r)},release(r){n.release(r)},dispose(){n.dispose()}}}function Wm(){return typeof navigator>"u"?void 0:navigator.gpu}function FO(n){return po.probe({gpu:Wm(),powerPreference:n?.powerPreference??"high-performance",rejectSoftware:n?.rejectSoftware})}function BO(n){const e=Wm();return e===void 0&&n?.adapter===void 0?Promise.reject(new S("E_NO_WEBGPU","navigator.gpu is undefined: this browser or context has no WebGPU",{reason:"navigator.gpu is undefined",hint:"WebGPU needs a supporting browser and a secure context (https or localhost)"})):po.create({powerPreference:"high-performance",...n,gpu:e,runtime:"browser"})}const zO=8,GO="call configureWebGpu({ acceptSoftware: true }) to accept the software adapter";function WO(n,e){return{acquire:async()=>{const t=e.acceptSoftware!==!0,r=await n.probe(t);if(!r.ok){const s=r.code==="E_SOFTWARE_ONLY"?GO:n.fixes[r.code]??null;throw new Oc(r.code,r.reason??r.code,s)}const o=await n.open(r,t,zO);try{const s=await kp(o);if(s.mismatch!==null)throw new Oc("E_DEVICE_INCORRECT",`the ${s.vendor} device computes a known prefix sum incorrectly (${s.mismatch.where})`);const{caps:i}=o;return{accelerator:UO(o),device:`${i.vendor} ${i.device===""?i.description:i.device}`,lost:o.lost.then(a=>a.message===""?a.reason:a.message)}}catch(s){throw o.dispose(),s}}}}function VO(n){return WO({probe:e=>FO({rejectSoftware:e}),open:(e,t,r)=>BO({adapter:e.adapter??void 0,rejectSoftware:t,warnUnreleasedSnapshots:r}),fixes:{}},n)}const jO=Object.freeze(Object.defineProperty({__proto__:null,gpuProvider:VO},Symbol.toStringTag,{value:"Module"})),qO="https://graphty.app/data/graph-samples/v1/";async function HO(n,e={}){if(!/^[a-z0-9][a-z0-9-]*$/.test(n))throw new RangeError(`not a dataset name: ${JSON.stringify(n)}`);const t=e.baseUrl??qO,r=new URL(`${n}.gsnp.gz`,t.endsWith("/")?t:`${t}/`),o=await(e.fetch??fetch)(r,{signal:e.signal??null});if(!o.ok||o.body===null)throw new Error(`fetching ${r.href} failed: HTTP ${o.status}`);return p2(await KO(new Uint8Array(await o.arrayBuffer())))}async function KO(n){if(n[0]!==31||n[1]!==139)return n;const e=new Blob([n]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}const YO=466688986;function Vm(n,e,t,r,o){const s=n>>>0,i=e>>>0,a=(YO^s^i)>>>0;let c=t+s|0,l=r+i|0;c=c+l|0,l=(l<<13|l>>>19)^c,c=c+l|0,l=(l<<15|l>>>17)^c,c=c+l|0,l=(l<<26|l>>>6)^c,c=c+l|0,l=(l<<6|l>>>26)^c,c=c+i|0,l=l+a+1|0,c=c+l|0,l=(l<<17|l>>>15)^c,c=c+l|0,l=(l<<29|l>>>3)^c,c=c+l|0,l=(l<<16|l>>>16)^c,c=c+l|0,l=(l<<24|l>>>8)^c,c=c+a|0,l=l+s+2|0,c=c+l|0,l=(l<<13|l>>>19)^c,c=c+l|0,l=(l<<15|l>>>17)^c,c=c+l|0,l=(l<<26|l>>>6)^c,c=c+l|0,l=(l<<6|l>>>26)^c,c=c+s|0,l=l+i+3|0,c=c+l|0,l=(l<<17|l>>>15)^c,c=c+l|0,l=(l<<29|l>>>3)^c,c=c+l|0,l=(l<<16|l>>>16)^c,c=c+l|0,l=(l<<24|l>>>8)^c,c=c+i|0,l=l+a+4|0,c=c+l|0,l=(l<<13|l>>>19)^c,c=c+l|0,l=(l<<15|l>>>17)^c,c=c+l|0,l=(l<<26|l>>>6)^c,c=c+l|0,l=(l<<6|l>>>26)^c,c=c+a|0,l=l+s+5|0,o[0]=c,o[1]=l}const Ps=4294967296,XO=9007199254740992;function QO(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}const JO=0;function pe(n){const e=n??JO;return jm(e),e}function jm(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError(`seed must be an integer in [0, 2^53), got ${String(n)}`)}class fe{constructor(e,t,r){this.key=new Uint32Array(2),this.out=new Uint32Array(2),this.counter=0,this.spare=-1,jm(e),this.seedLo=e>>>0,this.seedHi=Math.floor(e/Ps),this.domain=QO(t),this.reset(r)}reset(e){Vm(this.seedLo,this.seedHi,this.domain,e>>>0,this.key),this.counter=0,this.spare=-1}nextU32(){if(this.spare>=0){const t=this.spare;return this.spare=-1,t}const e=this.counter++;return Vm(this.key[0],this.key[1],e>>>0,Math.floor(e/Ps),this.out),this.spare=this.out[1],this.out[0]}nextFloat(){const e=this.nextU32()>>>5,t=this.nextU32()>>>6;return(e*67108864+t)/XO}nextBelow(e){if(e<=Ps){const o=e===1?0:4294967295>>>Math.clz32(e-1);for(;;){const s=(this.nextU32()&o)>>>0;if(s<e)return s}}const t=Math.ceil(e/Ps),r=4294967295>>>Math.clz32(t-1);for(;;){const s=((this.nextU32()&r)>>>0)*Ps+this.nextU32();if(s<e)return s}}nextSkip(e){return Math.floor(Ge(1-this.nextFloat())/e)}}function Ji(n,e){const t=n.nodeColumns?.[e];if(t===void 0||!ArrayBuffer.isView(t))throw new RangeError(`weights: the graph has no numeric node column "${e}"`);return t}function ZO(n,e,t){const r=n.src.length,o=new Float32Array(r),{src:s,dst:i}=n,a=new fe(t,"weights",0);switch(e.kind){case"uniform":{const c=e.min??0,l=e.max??1;if(!(Number.isFinite(c)&&Number.isFinite(l)&&c<=l))throw new RangeError(`weights: uniform needs finite min <= max, got ${c} and ${l}`);for(let u=0;u<r;u++)o[u]=c+(l-c)*a.nextFloat();break}case"integer":{const{min:c,max:l}=e;if(!(Number.isSafeInteger(c)&&Number.isSafeInteger(l)&&c<=l))throw new RangeError(`weights: integer needs integers min <= max, got ${c} and ${l}`);for(let u=0;u<r;u++)o[u]=c+a.nextBelow(l-c+1);break}case"exponential":{const c=e.mean??1;if(!(c>0&&Number.isFinite(c)))throw new RangeError(`weights: exponential needs a positive mean, got ${c}`);for(let l=0;l<r;l++)o[l]=-c*Ge(1-a.nextFloat());break}case"euclidean":{const c=Ji(n,"x"),l=Ji(n,"y"),u=n.nodeColumns?.z===void 0?null:Ji(n,"z");for(let d=0;d<r;d++){const f=c[s[d]]-c[i[d]],h=l[s[d]]-l[i[d]],g=u===null?0:u[s[d]]-u[i[d]];o[d]=Math.sqrt(f*f+h*h+g*g)}break}default:{const c=Ji(n,e.column),l=e.combine??"sum";for(let u=0;u<r;u++){const d=c[s[u]],f=c[i[u]];o[u]=e$(l,d,f)}}}return o}function e$(n,e,t){switch(n){case"source":return e;case"target":return t;case"sum":return e+t;case"mean":return(e+t)/2;case"product":return e*t;case"min":return Math.min(e,t);case"max":return Math.max(e,t);default:return Math.abs(e-t)}}function t$(n,e,t){return{...n,weights:ZO(n,e,pe(t))}}function oe(n,e){return e.weights===void 0?n:t$(n,e.weights,e.seed)}const Zi=["bull","chvatal","cubical","desargues","diamond","dodecahedral","frucht","heawood","hoffman-singleton","house","house-x","icosahedral","krackhardt-kite","moebius-kantor","octahedral","pappus","sedgewick-maze","tetrahedral","truncated-cube","truncated-tetrahedron","tutte"],qm={bull:[5,[0,1,0,2,1,2,1,3,2,4]],chvatal:[12,[0,1,0,4,0,6,0,9,1,2,1,5,1,7,2,3,2,6,2,8,3,4,3,7,3,9,4,5,4,8,5,10,5,11,6,10,6,11,7,8,7,11,8,10,9,10,9,11]],cubical:[8,[0,1,0,3,0,4,1,2,1,7,2,3,2,6,3,5,4,5,4,7,5,6,6,7]],desargues:[20,[0,1,0,19,0,5,1,2,1,16,2,3,2,11,3,4,3,14,4,5,4,9,5,6,6,7,6,15,7,8,7,18,8,9,8,13,9,10,10,11,10,19,11,12,12,13,12,17,13,14,14,15,15,16,16,17,17,18,18,19]],diamond:[4,[0,1,0,2,1,2,1,3,2,3]],dodecahedral:[20,[0,1,0,19,0,10,1,2,1,8,2,3,2,6,3,4,3,19,4,5,4,17,5,6,5,15,6,7,7,8,7,14,8,9,9,10,9,13,10,11,11,12,11,18,12,13,12,16,13,14,14,15,15,16,16,17,17,18,18,19]],frucht:[12,[0,1,0,6,0,7,1,2,1,7,2,3,2,8,3,4,3,9,4,5,4,9,5,6,5,10,6,10,7,11,8,11,8,9,10,11]],heawood:[14,[0,1,0,13,0,5,1,2,1,10,2,3,2,7,3,4,3,12,4,5,4,9,5,6,6,7,6,11,7,8,8,9,8,13,9,10,10,11,11,12,12,13]],"hoffman-singleton":[50,[0,1,0,2,0,3,0,6,0,7,0,8,0,9,1,17,1,12,1,26,1,27,1,28,1,29,2,10,2,11,2,13,2,14,2,15,2,16,3,4,3,5,3,30,3,35,3,40,3,45,4,11,4,17,4,34,4,39,4,44,4,49,5,12,5,10,5,33,5,38,5,43,5,48,6,22,6,18,6,31,6,39,6,43,6,47,7,34,7,23,7,19,7,37,7,41,7,48,8,33,8,36,8,24,8,20,8,42,8,49,9,32,9,38,9,44,9,25,9,21,9,46,10,17,10,18,10,19,10,20,10,21,11,12,11,32,11,37,11,42,11,47,12,31,12,36,12,41,12,46,13,30,13,26,13,22,13,36,13,44,13,48,14,31,14,27,14,23,14,38,14,40,14,49,15,34,15,35,15,28,15,24,15,43,15,46,16,33,16,39,16,41,16,45,16,29,16,25,17,22,17,23,17,24,17,25,18,32,18,26,18,35,18,41,18,49,19,30,19,27,19,39,19,42,19,46,20,31,20,37,20,28,20,44,20,45,21,34,21,36,21,40,21,47,21,29,22,33,22,37,22,40,22,46,23,32,23,36,23,43,23,45,24,30,24,38,24,41,24,47,25,31,25,35,25,42,25,48,26,34,26,38,26,42,26,45,27,33,27,35,27,44,27,47,28,32,28,39,28,40,28,48,29,30,29,37,29,43,29,49,30,31,30,32,31,34,32,33,33,34,35,36,35,37,36,39,37,38,38,39,40,41,40,42,41,44,42,43,43,44,45,46,45,47,46,49,47,48,48,49]],house:[5,[0,1,0,2,1,3,2,3,2,4,3,4]],"house-x":[5,[0,1,0,2,0,3,1,3,1,2,2,3,2,4,3,4]],icosahedral:[12,[0,1,0,5,0,7,0,8,0,11,1,2,1,5,1,6,1,8,2,3,2,6,2,8,2,9,3,4,3,6,3,9,3,10,4,5,4,6,4,10,4,11,5,6,5,11,7,8,7,9,7,10,7,11,8,9,9,10,10,11]],"krackhardt-kite":[10,[0,1,0,2,0,3,0,5,1,3,1,4,1,6,2,3,2,5,3,4,3,5,3,6,4,6,5,6,5,7,6,7,7,8,8,9]],"moebius-kantor":[16,[0,1,0,15,0,5,1,2,1,12,2,3,2,7,3,4,3,14,4,5,4,9,5,6,6,7,6,11,7,8,8,9,8,13,9,10,10,11,10,15,11,12,12,13,13,14,14,15]],octahedral:[6,[0,1,0,2,0,3,0,4,1,2,1,3,1,5,2,4,2,5,3,4,3,5,4,5]],pappus:[18,[0,1,0,17,0,5,1,2,1,8,2,3,2,13,3,4,3,10,4,5,4,15,5,6,6,7,6,11,7,8,7,14,8,9,9,10,9,16,10,11,11,12,12,13,12,17,13,14,14,15,15,16,16,17]],"sedgewick-maze":[8,[0,2,0,7,0,5,1,7,2,6,3,4,3,5,4,5,4,7,4,6]],tetrahedral:[4,[0,1,0,2,0,3,1,2,1,3,2,3]],"truncated-cube":[24,[0,1,0,2,0,4,1,11,1,14,2,3,2,4,3,6,3,8,4,5,5,16,5,18,6,7,6,8,7,10,7,12,8,9,9,17,9,20,10,11,10,12,11,14,12,13,13,21,13,22,14,15,15,19,15,23,16,17,16,18,17,20,18,19,19,23,20,21,21,22,22,23]],"truncated-tetrahedron":[12,[0,1,0,2,0,9,1,2,1,6,2,3,3,4,3,11,4,5,4,11,5,6,5,7,6,7,7,8,8,9,8,10,9,10,10,11]],tutte:[46,[0,1,0,2,0,3,1,4,1,26,2,10,2,11,3,18,3,19,4,5,4,33,5,6,5,29,6,7,6,27,7,8,7,14,8,9,8,38,9,10,9,37,10,39,11,12,11,39,12,13,12,35,13,14,13,15,14,34,15,16,15,22,16,17,16,44,17,18,17,43,18,45,19,20,19,45,20,21,20,41,21,22,21,23,22,40,23,24,23,27,24,25,24,32,25,26,25,31,26,33,27,28,28,29,28,32,29,30,30,31,30,33,31,32,34,35,34,38,35,36,36,37,36,39,37,38,40,41,40,44,41,42,42,43,42,45,43,44]]};function n$(n,e={}){const t=Object.prototype.hasOwnProperty.call(qm,n)?qm[n]:void 0;if(t===void 0)throw new RangeError(`unknown named graph "${n}"; see NAMED_GRAPH_NAMES`);const[r,o]=t,s=o.length/2,i=new Uint32Array(s),a=new Uint32Array(s);for(let c=0;c<s;c++)i[c]=o[2*c],a[c]=o[2*c+1];return oe({directed:!1,nodeCount:r,src:i,dst:a},e)}function j(n,e,t,r,o){return{name:n,plainName:e,type:"integer",default:t,min:r,...o===void 0?{}:{max:o}}}function Pt(n,e,t,r,o){return{name:n,plainName:e,type:"number",default:t,min:r,...o===void 0?{}:{max:o}}}function xt(n,e,t){return Pt(n,e,t,0,1)}function Dr(n,e,t){return{name:n,plainName:e,type:"boolean",default:t}}const ye=j("seed","Seed",0,0,Number.MAX_SAFE_INTEGER);function Ee(n,e=1){return j("n","Nodes",n,e)}function te(n,e,t,r){return{name:n,plainName:e,description:t,params:r,thumbnail:`generator-${n}.webp`}}Object.freeze([te("ak","AK flow network","A hard maximum-flow instance of 4k + 6 nodes, built to defeat augmenting-path methods.",[j("k","Size",4,1,499998)]),te("balanced-tree","Balanced tree","A rooted tree in which every inner node has the same number of children.",[j("branching","Children per node",3,1),j("height","Height",4,0)]),te("barabasi-albert","Barabasi-Albert","A scale-free network grown by preferential attachment: new nodes link to well-connected ones.",[Ee(150,2),j("m","Edges per new node",2,1),xt("triadProbability","Triangle closing",0),ye]),te("barbell","Barbell","Two complete graphs joined by a path.",[j("cliqueSize","Clique size",8,2),j("pathLength","Path length",6,0)]),te("bianconi-barabasi","Bianconi-Barabasi","Preferential attachment weighted by a random fitness per node, so a late node can still become a hub.",[Ee(150,2),j("m","Edges per new node",2,1),ye]),te("bipartite-configuration-model","Bipartite configuration model","A random two-sided network with a set degree on every left node.",[j("left","Left nodes",20,1),j("right","Right nodes",30,1),j("degree","Left degree",3,0),ye]),te("caveman","Caveman","Separate complete graphs: the extreme of community structure.",[j("cliques","Cliques",6,1),j("size","Clique size",6,1)]),te("chung-lu","Chung-Lu","A random network whose node degrees follow a power law in expectation.",[Ee(150),j("minDegree","Smallest degree",2,1),j("maxDegree","Largest degree",40,1),Pt("exponent","Degree exponent",2.5,0),ye]),te("circular-ladder","Circular ladder","Two cycles with every pair of matching nodes joined: a prism.",[Ee(20,3)]),te("complete","Complete graph","Every node joined to every other node.",[Ee(12)]),te("complete-bipartite","Complete bipartite","Two groups with every node of one joined to every node of the other.",[j("a","First group",6,0),j("b","Second group",8,0)]),te("complete-multipartite","Complete multipartite","Several equal groups with every pair of nodes in different groups joined.",[j("parts","Groups",3,1),j("partSize","Group size",4,1)]),te("configuration-model","Configuration model","A random network with a power-law degree sequence, wired by pairing edge ends at random.",[Ee(150),j("minDegree","Smallest degree",2,1),j("maxDegree","Largest degree",20,1),Pt("exponent","Degree exponent",2.5,0),ye]),te("connected-caveman","Connected caveman","A ring of near-complete groups, each with one edge rewired to its neighbor group.",[j("cliques","Cliques",8,2),j("size","Clique size",6,2)]),te("cycle","Cycle","Nodes joined in a single ring.",[Ee(30)]),te("degree-corrected-sbm","Degree-corrected block model","Communities with power-law degrees inside them: a stochastic block model with hubs.",[j("blocks","Communities",3,1),j("blockSize","Community size",40,1),j("minDegree","Smallest degree",3,1),j("maxDegree","Largest degree",15,1),Pt("exponent","Degree exponent",2.5,0),xt("mixing","Mixing",.05),ye]),te("directed-configuration-model","Directed configuration model","A random directed network in which every node has the same in-degree and out-degree.",[Ee(60),j("degree","Degree",2,0),ye]),te("duplication-divergence","Duplication-divergence","A network grown by copying nodes and losing some copied edges, a model of protein interactions.",[Ee(100,2),Pt("retention","Edge retention",.4,0,1),ye]),te("empty","Empty graph","Nodes with no edges at all.",[Ee(20,0)]),te("erdos-renyi","Erdos-Renyi","A random network in which every pair of nodes is joined with the same probability.",[Ee(100,0),xt("p","Edge probability",.04),Dr("directed","Directed",!1),ye]),te("erdos-renyi-gnm","Erdos-Renyi (fixed edges)","A random network with an exact number of edges placed uniformly at random.",[Ee(100,0),j("m","Edges",200,0),ye]),te("forest-fire","Forest fire","A directed network grown by new nodes burning through their neighbors' links, as citation networks grow.",[Ee(100),Pt("forward","Forward burning",.35,0,.999),Pt("backward","Backward burning",.3,0),ye]),te("genrmf","GENRMF flow network","A stack of grid frames joined by random arcs, a standard maximum-flow benchmark.",[j("a","Frame side",3,1),j("b","Frames",4,1),j("c1","Smallest capacity",1,0),j("c2","Largest capacity",100,0),ye]),te("grid","Grid","A two-dimensional square lattice.",[j("rows","Rows",15,1),j("cols","Columns",15,1),Dr("periodic","Wrap around",!1),Dr("diagonals","Diagonals",!1)]),te("grid-3d","3D grid","A three-dimensional cubic lattice.",[j("rows","Rows",6,1),j("cols","Columns",6,1),j("layers","Layers",4,1),Dr("periodic","Wrap around",!1),Dr("diagonals","Diagonals",!1)]),te("grid-flow-network","Grid flow network","A grid of arcs with random capacities between a source on the left and a sink on the right.",[j("rows","Rows",8,1),j("cols","Columns",8,2),j("minCapacity","Smallest capacity",1,0),j("maxCapacity","Largest capacity",10,0),ye]),te("hexagonal-lattice","Hexagonal lattice","A honeycomb of hexagons.",[j("rows","Rows",6,1),j("cols","Columns",8,1)]),te("hyperbolic","Hyperbolic random graph","Points in the hyperbolic plane joined when close, giving hubs, clustering and short paths at once.",[Ee(150,0),Pt("averageDegree","Average degree",4,.01),Pt("exponent","Degree exponent",2.5,2.01),Pt("temperature","Temperature",0,0,.99),ye]),te("hypercube","Hypercube","The corners of a cube in any number of dimensions, joined along its edges.",[j("dimension","Dimensions",4,0,20)]),te("knn","Nearest neighbors","Random points, each joined to the points closest to it.",[Ee(150,0),j("k","Neighbors per node",3,0),Dr("directed","Directed",!1),ye]),te("kronecker","Kronecker graph","A self-similar directed network made by repeatedly multiplying a small core-periphery pattern.",[j("power","Power",7,1,20),ye]),te("ladder","Ladder","Two paths with every pair of matching nodes joined.",[Ee(20)]),te("layered-flow-network","Layered flow network","Layers of nodes between a source and a sink, with random arcs from each layer to the next.",[j("layers","Layers",3,1),j("width","Layer width",6,1),xt("p","Arc probability",.5),j("minCapacity","Smallest capacity",1,0),j("maxCapacity","Largest capacity",10,0),ye]),te("lfr","LFR benchmark","A benchmark network with planted communities and power-law degrees, for testing community detection.",[Ee(250),j("minDegree","Smallest degree",4,1),j("maxDegree","Largest degree",30,1),Pt("degreeExponent","Degree exponent",2.5,0),j("minCommunity","Smallest community",20,1),j("maxCommunity","Largest community",60,1),Pt("communityExponent","Community size exponent",1.5,0),xt("mixing","Mixing",.1),ye]),te("lollipop","Lollipop","A complete graph with a path hanging from it.",[j("cliqueSize","Clique size",8,1),j("pathLength","Path length",10,0)]),te("mobius-ladder","Mobius ladder","A ladder bent into a ring with a half twist.",[Ee(20,4)]),te("named","Named graph","A famous small graph from graph theory, chosen by name.",[{name:"name",plainName:"Graph",type:"choice",default:"frucht",choices:Zi}]),te("newman-watts","Newman-Watts","A ring lattice with random shortcuts added: a small world.",[Ee(60,3),j("k","Ring neighbors",4,2),xt("p","Shortcut probability",.1),ye]),te("path","Path","Nodes joined in a single line.",[Ee(30)]),te("petersen","Petersen graph","The ten-node graph that is the counterexample to many conjectures.",[]),te("planted-partition","Planted partition","Equal groups with dense links inside each group and sparse links between them.",[j("groups","Groups",4,1),j("groupSize","Group size",30,1),xt("pIn","Inside probability",.2),xt("pOut","Between probability",.005),ye]),te("price","Price citation model","A directed citation network in which well-cited papers attract more citations.",[Ee(150),j("citations","Citations per paper",2,1),Pt("attractiveness","Attractiveness",1,.001),ye]),te("random-apollonian","Random Apollonian network","A planar network grown by repeatedly splitting a random triangle in three.",[Ee(40,3),ye]),te("random-bipartite","Random bipartite","Two groups with every pair across them joined with the same probability.",[j("n1","First group",15,0),j("n2","Second group",20,0),xt("p","Edge probability",.15),ye]),te("random-dag","Random layered DAG","Layers of nodes with random arcs from each layer to the next.",[j("layers","Layers",5,1),j("width","Layer width",8,1),xt("p","Arc probability",.25),ye]),te("random-geometric","Random geometric","Random points in a square, joined when they are closer than a set distance.",[Ee(200,0),Pt("radius","Radius",.1,0),Dr("periodic","Wrap around",!1),ye]),te("random-order-dag","Random ordered DAG","Nodes in a fixed order with each forward arc present at the same probability.",[Ee(50,0),xt("p","Arc probability",.08),ye]),te("random-recursive-tree","Random recursive tree","A tree grown by attaching each new node to a uniformly random earlier one.",[Ee(100),ye]),te("random-regular","Random regular","A random network in which every node has the same degree.",[Ee(60,0),j("d","Degree",3,0),ye]),te("random-tree","Random tree","A tree drawn uniformly from all labeled trees on its nodes.",[Ee(100),ye]),te("ring-of-cliques","Ring of cliques","Complete graphs joined one to the next in a ring.",[j("cliques","Cliques",8,2),j("size","Clique size",5,2)]),te("rmat","R-MAT","A skewed, scale-free directed network made by recursive quadrant choice, as in Graph500.",[j("scale","Scale (log2 of nodes)",7,0,31),j("edgeFactor","Edges per node",4,0),ye]),te("star","Star","One hub joined to every other node.",[Ee(20)]),te("stochastic-block-model","Stochastic block model","Blocks of nodes whose link probability depends only on the two blocks.",[j("blocks","Blocks",3,1),j("blockSize","Block size",40,1),xt("pIn","Inside probability",.1),xt("pOut","Between probability",.005),ye]),te("triangular-lattice","Triangular lattice","A plane tiled with triangles.",[j("rows","Rows",8,1),j("cols","Columns",10,1)]),te("watts-strogatz","Watts-Strogatz","A ring lattice with some edges rewired at random: the classic small world.",[Ee(60,3),j("k","Ring neighbors",4,2),xt("beta","Rewiring probability",.1),ye]),te("waxman","Waxman","Random points joined with a probability that falls with their distance, a model of the Internet.",[Ee(200,0),Pt("alpha","Distance scale",.05,1e-4),xt("beta","Density",1),ye]),te("wheel","Wheel","A cycle with a hub joined to every node of it.",[Ee(20)]),te("wilson-maze","Maze","A random spanning tree of a grid: a perfect maze.",[j("rows","Rows",12,1),j("cols","Columns",12,1),ye])]);const r$=["road-ny","ogbn-arxiv","go-basic","disease-ontology","bioplex3-hct116","com-dblp"],Hm=[...["karate","florentine-families","davis-southern-women","les-miserables","football","political-books","dolphins","contiguous-usa","knuth-miles","celegans-neural","political-blogs","openflights","venice-transit","yeast-perturbation","stelzl-interactome","wikipathways-senescence-autophagy","go-slim-generic"],...r$];function G(n,e,t,r=Te){if(!Number.isInteger(e)||e<t||e>r)throw new RangeError(`${n} must be an integer in [${t}, ${r}], got ${String(e)}`)}function rt(n,e){if(!(e>=0&&e<=1))throw new RangeError(`${n} must be a probability in [0, 1], got ${String(e)}`)}function Ce(n){if(n>Te)throw new RangeError(`the graph would have ${n} edges, above the limit of ${Te}`)}class le{constructor(e){this.length=0;const t=Math.max(16,Math.min(e,Te));this.src=new Uint32Array(t),this.dst=new Uint32Array(t)}push(e,t){this.length===this.src.length&&this.grow(),this.src[this.length]=e,this.dst[this.length]=t,this.length++}finish(){return this.length===this.src.length?{src:this.src,dst:this.dst}:{src:this.src.slice(0,this.length),dst:this.dst.slice(0,this.length)}}grow(){Ce(this.length+1);const e=Math.min(this.src.length*2,Te),t=new Uint32Array(e),r=new Uint32Array(e);t.set(this.src),r.set(this.dst),this.src=t,this.dst=r}}function xs(n,e){const t=n*e;return Ce(t),new le(Math.ceil(t+6*Math.sqrt(t*(1-e))+16))}function Cs(n,e,t,r,o,s,i){if(e===0||o>=s)return;if(e===1){for(let c=o;c<s;c++)i.push(r,c);return}let a=o+n.nextSkip(t);for(;a<s;)i.push(r,a),a+=1+n.nextSkip(t)}function ae(n,e,t,r){const{src:o,dst:s}=e.finish();return r===void 0?{directed:t,nodeCount:n,src:o,dst:s}:{directed:t,nodeCount:n,src:o,dst:s,nodeColumns:r}}function o$(n,e){const t=new fe(e,"bipartite-matching",0),r=new Uint32Array(n);for(let o=0;o<n;o++)r[o]=o;for(let o=n-1;o>0;o--){const s=t.nextBelow(o+1),i=r[o];r[o]=r[s],r[s]=i}return r}function s$(n,e,t,r,o){const{n1:s,n2:i,p:a}=n,c=pe(n.seed),l=Ge(1-a),u=new fe(c,"bipartite",0);for(let d=t;d<r;d++){u.reset(d);let f=e===null?-1:e[d];const h=g=>{f>=0&&f<g&&o.push(d,s+f),f>=0&&f<=g&&(f=-1),o.push(d,s+g)};if(a===1)for(let g=0;g<i;g++)h(g);else if(a>0){let g=u.nextSkip(l);for(;g<i;)h(g),g+=1+u.nextSkip(l)}f>=0&&o.push(d,s+f)}}function i$(n){const{n1:e,n2:t,p:r}=n;G("n1",e,0),G("n2",t,0),G("n1 + n2",e+t,0),rt("p",r);const o=pe(n.seed);let s=null;if(n.perfectMatching===!0){if(e!==t)throw new RangeError(`perfectMatching needs n1 === n2, got ${e} and ${t}`);s=o$(e,o)}const i=xs(e*t,r);s$(n,s,0,e,i);const a=new Uint8Array(e+t).fill(1,e);return oe(ae(e+t,i,!1,{side:a}),n)}function a$(n){const{sizes:e,probabilities:t}=n,r=pe(n.seed),o=e.length;if(G("sizes.length",o,1),t.length!==o)throw new RangeError(`probabilities must be ${o} x ${o}`);const s=[0];for(let c=0;c<o;c++){if(G(`sizes[${c}]`,e[c],0),s.push(s[c]+e[c]),t[c].length!==o)throw new RangeError(`probabilities must be ${o} x ${o}`);for(let l=0;l<o;l++)if(rt(`probabilities[${c}][${l}]`,t[c][l]),t[c][l]!==t[l][c])throw new RangeError(`probabilities must be symmetric: [${c}][${l}] differs from [${l}][${c}]`)}const i=s[o];G("the total size",i,0);const a=new Uint32Array(i);for(let c=0;c<o;c++)a.fill(c,s[c],s[c+1]);return{n:i,seed:r,starts:s,block:a,p:t,logQ:t.map(c=>c.map(l=>Ge(1-l)))}}function c$(n,e,t,r){const{starts:o,block:s,p:i,logQ:a}=n,c=new fe(n.seed,"sbm",0),l=o.length-1;for(let u=e;u<t;u++){c.reset(u);const d=s[u];for(let f=d;f<l;f++)Cs(c,i[d][f],a[d][f],u,f===d?u+1:o[f],o[f+1],r)}}function Km(n){const e=a$(n);let t=0,r=0;for(let s=0;s<e.starts.length-1;s++)for(let i=s;i<e.starts.length-1;i++){const a=e.starts[s+1]-e.starts[s],c=e.starts[i+1]-e.starts[i],l=s===i?a*(a-1)/2:a*c;t+=l*e.p[s][i],r+=l}const o=xs(r,r===0?0:t/r);return c$(e,0,e.n,o),oe(ae(e.n,o,!1,{community:e.block}),n)}function l$(n){const{groups:e,groupSize:t,pIn:r,pOut:o,seed:s}=n;return G("groups",e,1),G("groupSize",t,1),Km({sizes:new Array(e).fill(t),probabilities:Array.from({length:e},(i,a)=>Array.from({length:e},(c,l)=>a===l?r:o)),seed:s,weights:n.weights})}function To(n,e,t){for(let r=e;r<e+t;r++)for(let o=r+1;o<e+t;o++)n.push(r,o)}function u$(n){const{n:e}=n;G("n",e,0);const t=new le(e);for(let r=0;r+1<e;r++)t.push(r,r+1);return oe(ae(e,t,!1),n)}function d$(n){const{n:e}=n;G("n",e,3);const t=new le(e);for(let r=0;r+1<e;r++)t.push(r,r+1);return t.push(e-1,0),oe(ae(e,t,!1),n)}function f$(n){const{n:e}=n;G("n",e,1);const t=new le(e);for(let r=1;r<e;r++)t.push(0,r);return oe(ae(e,t,!1),n)}function h$(n){const{n:e}=n;G("n",e,4);const t=new le(2*e);for(let r=1;r<e;r++)t.push(0,r);for(let r=1;r+1<e;r++)t.push(r,r+1);return t.push(e-1,1),oe(ae(e,t,!1),n)}function g$(n){const{n:e}=n;G("n",e,0);const t=e*(e-1)/2;Ce(t);const r=new le(t);return To(r,0,e),oe(ae(e,r,!1),n)}function w$(n){const{a:e,b:t}=n;G("a",e,0),G("b",t,0),G("a + b",e+t,0),Ce(e*t);const r=new le(e*t);for(let s=0;s<e;s++)for(let i=0;i<t;i++)r.push(s,e+i);const o=new Uint8Array(e+t).fill(1,e);return oe(ae(e+t,r,!1,{side:o}),n)}function p$(n){const{dimension:e}=n;G("dimension",e,0,26);const t=2**e,r=new le(e*t/2);for(let o=0;o<t;o++)for(let s=0;s<e;s++){const i=o|1<<s;i!==o&&r.push(o,i)}return oe(ae(t,r,!1),n)}function m$(n){const{n:e}=n;return G("n",e,1),G("2n",2*e,2),oe(ae(2*e,Ym(e),!1),n)}function y$(n){const{cliqueSize:e,pathLength:t}=n;G("cliqueSize",e,2),G("pathLength",t,0);const r=2*e+t;G("2 * cliqueSize + pathLength",r,4),Ce(e*(e-1)+t+1);const o=new le(e*(e-1)+t+1);To(o,0,e);for(let s=e-1;s<e+t;s++)o.push(s,s+1);return To(o,e+t,e),oe(ae(r,o,!1),n)}function b$(n){const{cliqueSize:e,pathLength:t}=n;G("cliqueSize",e,2),G("pathLength",t,0),G("cliqueSize + pathLength",e+t,2),Ce(e*(e-1)/2+t);const r=new le(e*(e-1)/2+t);To(r,0,e);for(let o=e-1;o+1<e+t;o++)r.push(o,o+1);return oe(ae(e+t,r,!1),n)}function iu(n,e){const t=new Uint32Array(n*e);for(let r=0;r<n;r++)t.fill(r,r*e,(r+1)*e);return t}function v$(n){const{cliques:e,size:t}=n;G("cliques",e,1),G("size",t,1);const r=e*t;G("cliques * size",r,1),Ce(r*(t-1)/2);const o=new le(r*(t-1)/2);for(let s=0;s<e;s++)To(o,s*t,t);return oe(ae(r,o,!1,{community:iu(e,t)}),n)}function A$(n){const{cliques:e,size:t}=n;G("cliques",e,2),G("size",t,2);const r=e*t;G("cliques * size",r,4),Ce(r*(t-1)/2);const o=new le(r*(t-1)/2);for(let s=0;s<e;s++){const i=s*t;for(let a=i;a<i+t;a++)for(let c=a+1;c<i+t;c++)a===i&&c===i+1?o.push(i,(i-1+r)%r):o.push(a,c)}return oe(ae(r,o,!1,{community:iu(e,t)}),n)}function E$(n){const{branching:e,height:t}=n;G("branching",e,1),G("height",t,0);let r=0,o=1;for(let i=0;i<=t;i++)r+=o,o*=e,G("node count",r,1);const s=new le(r);for(let i=1;i<r;i++)s.push(Math.floor((i-1)/e),i);return oe(ae(r,s,!1),n)}function _$(n={}){const e=new le(15);for(let t=0;t<5;t++)e.push(t,(t+1)%5);for(let t=0;t<5;t++)e.push(t,t+5);for(let t=0;t<5;t++)e.push(5+t,5+(t+2)%5);return oe(ae(10,e,!1),n)}function I$(n){return G("n",n.n,0),oe(ae(n.n,new le(0),!1),n)}function k$(n){const{sizes:e}=n,t=[0];for(let a=0;a<e.length;a++)G(`sizes[${a}]`,e[a],0),t.push(t[a]+e[a]);const r=t[e.length];G("the total size",r,0);let o=r*(r-1)/2;for(const a of e)o-=a*(a-1)/2;Ce(o);const s=new Uint32Array(r);for(let a=0;a<e.length;a++)s.fill(a,t[a],t[a+1]);const i=new le(o);for(let a=0;a<r;a++)for(let c=t[s[a]+1];c<r;c++)i.push(a,c);return oe(ae(r,i,!1,{part:s}),n)}function S$(n){const{n:e}=n;G("n",e,3),Ce(3*e);const t=Ym(e);return t.push(e-1,0),t.push(2*e-1,e),oe(ae(2*e,t,!1),n)}function P$(n){const{n:e}=n;G("n",e,3),Ce(3*e);const t=new le(3*e);for(let r=0;r+1<2*e;r++)t.push(r,r+1);t.push(2*e-1,0);for(let r=0;r<e;r++)t.push(r,r+e);return oe(ae(2*e,t,!1),n)}function Ym(n){const e=new le(3*n);for(let t=0;t<2;t++)for(let r=0;r+1<n;r++)e.push(t*n+r,t*n+r+1);for(let t=0;t<n;t++)e.push(t,n+t);return e}function x$(n){const{cliques:e,size:t}=n;G("cliques",e,2),G("size",t,2);const r=e*t;G("cliques * size",r,4);const o=r*(t-1)/2+e;Ce(o);const s=new le(o);for(let i=0;i<e;i++)To(s,i*t,t),s.push(i*t+1,(i+1)*t%r);return oe(ae(r,s,!1,{community:iu(e,t)}),n)}function C$(n,e){return n===0?e===0?1:e>0?0:1/0:Qr(e*Ge(n))}const N$=2**24;function T$(n,e){if(!(Number.isFinite(e)&&e>=0))throw new RangeError(`${n} must be a finite number >= 0, got ${String(e)}`)}function Xm(n,e,t,r){T$(n[0],e),G(n[1],t,1),G(n[2],r,t,Math.min(Te,t+N$-1));const o=r-t+1,s=new Float64Array(o);let i=0;for(let a=0;a<o;a++)i+=C$(t+a,-e),s[a]=i;return a=>{const c=a.nextFloat()*i;let l=0,u=o-1;for(;l<u;){const d=l+u>>>1;s[d]>c?u=d:l=d+1}return t+l}}function O$(n,e,t){let r=0;for(const s of n)r+=s;if(r%2===0)return;const o=n.length-1;if(n[o]<t)n[o]++;else if(n[o]>e)n[o]--;else throw new RangeError(`cannot make the degree sum even: every degree is ${e} and n is odd`)}function Ns(n,e){G(`${n}.length`,e.length,0);let t=0;for(let r=0;r<e.length;r++){const o=e[r];Number.isInteger(o)&&o>=0&&o<=Te||G(`${n}[${r}]`,o,0),t+=o}return Ce(t/2),t}function Ts(n,e){if(e!==void 0&&e!=="keep"&&e!=="erase")throw new RangeError(`${n} must be "keep" or "erase", got ${e}`);return e==="keep"}function lr(n,e,t=0){const r=new Uint32Array(e);let o=0;for(let s=0;s<n.length;s++)r.fill(s+t,o,o+n[s]),o+=n[s];return r}function Oo(n,e){for(let t=n.length-1;t>0;t--){const r=e.nextBelow(t+1),o=n[t];n[t]=n[r],n[r]=o}}function au(n,e,t,r,o){const{directed:s,keepLoops:i,keepMulti:a,group:c}=r,l=e.length,u=new Uint8Array(l).fill(1);for(let d=0;d<l;d++){const f=e[d],h=t[d];(!i&&f===h||c!==void 0&&c[f]===c[h])&&(u[d]=0)}if(!a){const d=p=>s?e[p]:Math.min(e[p],t[p]),f=new Uint32Array(n+1);for(let p=0;p<l;p++)f[d(p)+1]++;for(let p=0;p<n;p++)f[p+1]+=f[p];const h=f.slice(0,n),g=new Uint32Array(l);for(let p=0;p<l;p++)g[h[d(p)]++]=p;const w=new Uint32Array(n);for(let p=0;p<l;p++){const m=g[p];if(u[m]===0)continue;const y=d(m),b=s?t[m]:Math.max(e[m],t[m]);w[b]===y+1?u[m]=0:w[b]=y+1}}for(let d=0;d<l;d++)u[d]===1&&o.push(e[d],t[d])}function cu(n,e,t,r,o,s){const i=e.length/2,a=new Uint32Array(i),c=new Uint32Array(i);for(let l=0;l<i;l++)a[l]=e[2*l],c[l]=e[2*l+1];au(n,a,c,{directed:!1,keepLoops:t,keepMulti:r,group:s},o)}function $$(n){const{degrees:e}=n,t=pe(n.seed),r=Ts("selfLoops",n.selfLoops),o=Ts("multiEdges",n.multiEdges),s=Ns("degrees",e);if(s%2!==0)throw new RangeError(`the degree sum must be even, got ${s}`);const i=e.length,a=lr(e,s);Oo(a,new fe(t,"configuration",0));const c=new le(s/2);return cu(i,a,r,o,c),oe(ae(i,c,!1),n)}function R$(n){const{outDegrees:e,inDegrees:t}=n,r=pe(n.seed),o=Ts("selfLoops",n.selfLoops),s=Ts("multiEdges",n.multiEdges),i=Ns("outDegrees",e),a=Ns("inDegrees",t);if(e.length!==t.length)throw new RangeError("outDegrees and inDegrees must have the same length");if(i!==a)throw new RangeError(`the out-degree sum (${i}) must equal the in-degree sum (${a})`);const c=e.length,l=lr(t,a);Oo(l,new fe(r,"configuration-directed",0));const u=new le(i);return au(c,lr(e,i),l,{directed:!0,keepLoops:o,keepMulti:s},u),oe(ae(c,u,!0),n)}function D$(n){const{leftDegrees:e,rightDegrees:t}=n,r=pe(n.seed),o=Ts("multiEdges",n.multiEdges),s=Ns("leftDegrees",e),i=Ns("rightDegrees",t);if(s!==i)throw new RangeError(`the left degree sum (${s}) must equal the right degree sum (${i})`);const a=e.length,c=a+t.length;G("the node count",c,0);const l=lr(t,i,a);Oo(l,new fe(r,"bipartite-configuration",0));const u=new le(s);au(c,lr(e,s),l,{directed:!1,keepLoops:!0,keepMulti:o},u);const d=new Uint8Array(c).fill(1,a);return oe(ae(c,u,!1,{side:d}),n)}function Qm(n){G("expectedDegrees.length",n.length,0);let e=0;for(let t=0;t<n.length;t++){if(!(Number.isFinite(n[t])&&n[t]>=0))throw new RangeError(`expectedDegrees[${t}] must be a finite number >= 0, got ${String(n[t])}`);e+=n[t]}return e}function Jm(n,e,t,r,o,s){const i=n.length,a=new Uint32Array(i),c=new Uint32Array(i);for(let u=0;u<i;u++)a[u]=u;for(let u=0;u+1<e.length;u++)a.subarray(e[u],e[u+1]).sort((d,f)=>n[f]-n[d]||d-f),c.fill(u,e[u],e[u+1]);const l=Float64Array.from(a,u=>n[u]);return{n:i,seed:r,domain:o,order:a,weight:l,rowBlock:c,starts:e,factor:t,total:s}}function L$(n){const e=pe(n.seed),t=Qm(n.expectedDegrees),r=n.expectedDegrees.length;return Jm(n.expectedDegrees,[0,r],[[t>0?1/t:0]],e,"chung-lu",t)}function M$(n,e,t,r){const{order:o,weight:s,rowBlock:i,starts:a,factor:c}=n,l=new fe(n.seed,n.domain,0),u=a.length-1;for(let d=e;d<t;d++){l.reset(d);const f=i[d];for(let h=f;h<u;h++){const g=c[f][h]*s[d];let w=h===f?d+1:a[h];const p=a[h+1];if(g===0||w>=p)continue;let m=Math.min(1,g*s[w]);for(;w<p&&m>0;){if(m!==1){const b=Ge(1-m);if(b===0||(w+=l.nextSkip(b),w>=p))break}const y=Math.min(1,g*s[w]);l.nextFloat()<y/m&&r.push(o[d],o[w]),m=y,w++}}}}function Zm(n,e,t){const r=n.total/2;Ce(r);const o=new le(Math.ceil(r+6*Math.sqrt(r)+16));return M$(n,0,n.n,o),oe(ae(n.n,o,!1,e),t)}function U$(n){return Zm(L$(n),void 0,n)}function F$(n){const{sizes:e,expectedDegrees:t,mixing:r}=n,o=pe(n.seed);G("sizes.length",e.length,1),rt("mixing",r);const s=Qm(t),i=[0];for(let d=0;d<e.length;d++)G(`sizes[${d}]`,e[d],0),i.push(i[d]+e[d]);if(i[e.length]!==t.length)throw new RangeError(`the sizes sum to ${i[e.length]}, but expectedDegrees has ${t.length} entries`);const a=e.map((d,f)=>{let h=0;for(let g=i[f];g<i[f+1];g++)h+=t[g];return h}),c=s>0?r/s:0,l=a.map(d=>d>0?(1-r)/d:0),u=a.map((d,f)=>a.map((h,g)=>f===g?l[f]:c));return Jm(t,i,u,o,"dcsbm",s)}function B$(n){const e=F$(n),t=new Uint32Array(e.n);for(let r=0;r+1<e.starts.length;r++)t.fill(r,e.starts[r],e.starts[r+1]);return Zm(e,{community:t},n)}const lu=100,z$=1e3;function G$(n,e,t,r,o){o.fill(0);const s=(c,l)=>{const u=c*e;for(let d=u;d<u+o[c];d++)if(r[d]===l)return!0;return!1},i=new Uint32Array(n);let a=lr(new Uint32Array(n).fill(e),n*e);for(let c=0;c<z$&&a.length>0;c++){Oo(a,t);const l=[];for(let g=0;g<a.length;g+=2){const w=Math.min(a[g],a[g+1]),p=Math.max(a[g],a[g+1]);if(w!==p&&!s(w,p))r[w*e+o[w]++]=p,r[p*e+o[p]++]=w;else for(const m of[w,p])i[m]++===0&&l.push(m)}l.sort((g,w)=>g-w);let u=l.length===0;for(let g=0;g<l.length&&!u;g++)for(let w=g+1;w<l.length&&!u;w++)u=!s(l[g],l[w]);if(!u)return!1;let d=0;for(const g of l)d+=i[g];const f=new Uint32Array(d);let h=0;for(const g of l)f.fill(g,h,h+i[g]),h+=i[g],i[g]=0;a=f}return a.length===0}function W$(n){const{n:e,d:t}=n,r=pe(n.seed);if(G("n",e,0),G("d",t,0,Math.max(0,e-1)),e*t%2!==0)throw new RangeError(`n * d must be even, got ${e} * ${t}`);Ce(e*t/2);const o=new le(e*t/2);if(t>0){const s=new Uint32Array(e*t),i=new Uint32Array(e),a=new fe(r,"random-regular",0);let c=0;for(;c<lu&&(a.reset(c),!G$(e,t,a,s,i));c++);if(c===lu)throw new RangeError(`randomRegularGraph found no ${t}-regular graph on ${e} nodes in ${lu} attempts`);V$(e,t,s,o)}return oe(ae(e,o,!1),n)}function V$(n,e,t,r){for(let o=0;o<n;o++){const s=t.subarray(o*e,o*e+e).sort();for(const i of s)i>o&&r.push(o,i)}}function e0(n,e){if(e!==void 0&&e!=="keep"&&e!=="erase")throw new RangeError(`${n} must be "keep" or "erase", got ${e}`)}function t0(n,e,t,r,o,s){const i=r.directed??!0,a=e.length;if(r.permute===!0){const u=new Uint32Array(n);for(let f=0;f<n;f++)u[f]=f;const d=new fe(o,s,0);for(let f=n-1;f>0;f--){const h=d.nextBelow(f+1),g=u[f];u[f]=u[h],u[h]=g}for(let f=0;f<a;f++)e[f]=u[e[f]],t[f]=u[t[f]]}const c=new Uint8Array(a).fill(1);if(r.selfLoops==="erase")for(let u=0;u<a;u++)e[u]===t[u]&&(c[u]=0);if(r.multiEdges==="erase"){const u=i?e:e.map((h,g)=>Math.min(h,t[g])),d=i?t:e.map((h,g)=>Math.max(h,t[g])),f=new Uint32Array(a);for(let h=0;h<a;h++)f[h]=h;f.sort((h,g)=>u[h]-u[g]||d[h]-d[g]||h-g);for(let h=1;h<a;h++){const g=f[h-1],w=f[h];u[g]===u[w]&&d[g]===d[w]&&(c[w]=0)}}const l=new le(a);for(let u=0;u<a;u++)c[u]===1&&l.push(e[u],t[u]);return ae(n,l,i)}function n0(n){return e0("selfLoops",n.selfLoops),e0("multiEdges",n.multiEdges),pe(n.seed)}function j$(n){const{initiator:e,power:t}=n,r=e.length;G("initiator.length",r,1);let o=0;for(let p=0;p<r;p++){G(`initiator[${p}].length`,e[p].length,r,r);for(const m of e[p])rt(`initiator[${p}] entries`,m),o+=m}G("power",t,1,64);let s=1,i=1;for(let p=0;p<t;p++)s*=r,i*=o;G("k^power (the node count)",s,1);const a=n.edges??Math.round(i);if(Ce(a),G("edges",a,0),a>0&&o===0)throw new RangeError("edges must be 0 when the initiator is all zeros");const c=n0(n),l=r*r,u=new Float64Array(l);let d=0,f=0;for(let p=0;p<l;p++){const m=e[Math.floor(p/r)][p%r];d+=m,u[p]=d/o,m>0&&(f=p)}u.fill(1,f);const h=new Uint32Array(a),g=new Uint32Array(a),w=new fe(c,"kronecker",0);for(let p=0;p<a;p++){w.reset(p);let m=0,y=0;for(let b=0;b<t;b++){const v=w.nextFloat();let A=0;for(;v>=u[A];)A++;m=m*r+Math.floor(A/r),y=y*r+A%r}h[p]=m,g[p]=y}return oe(t0(s,h,g,n,c,"kronecker-permute"),n)}function q$(n){const{scale:e}=n,t=n.edgeFactor??16,r=n.a??.57,o=n.b??.19,s=n.c??.19,i=n.d??.05;if(G("scale",e,0,31),G("edgeFactor",t,0),rt("a",r),rt("b",o),rt("c",s),rt("d",i),Math.abs(r+o+s+i-1)>1e-9)throw new RangeError(`a + b + c + d must be 1, got ${r+o+s+i}`);const a=2**e,c=t*a;Ce(c);const l=n0(n),u=r+o,d=r+o+s,f=new Uint32Array(c),h=new Uint32Array(c),g=new fe(l,"rmat",0);for(let w=0;w<c;w++){g.reset(w);let p=0,m=0;for(let y=0;y<e;y++){const b=g.nextFloat();p*=2,m*=2,b<r||(b<u?m+=1:b<d?p+=1:(p+=1,m+=1))}f[w]=p,h[w]=m}return oe(t0(a,f,h,n,l,"rmat-permute"),n)}function H$(n){const{n:e,citations:t}=n,r=n.attractiveness??1;if(G("n",e,1),G("citations",t,1),!(r>0&&Number.isFinite(r)))throw new RangeError(`attractiveness must be a positive number, got ${String(r)}`);const o=pe(n.seed),s=Math.min(t,e),i=s*(s-1)/2+(e-s)*t;Ce(i);const a=new fe(o,"price",0),c=new le(i),l=new Int32Array(e).fill(-1);for(let u=1;u<e;u++){const d=c.length;if(u<=t){for(let f=0;f<u;f++)c.push(u,f);continue}K$(a,c,l,u,t,d+r*u)}return oe(ae(e,c,!0),n)}function K$(n,e,t,r,o,s){const i=e.length;for(let a=0;a<o;){const l=n.nextFloat()*s<i?e.dst[n.nextBelow(i)]:n.nextBelow(r);t[l]!==r&&(t[l]=r,e.push(r,l),a++)}}function Y$(n,e,t,r){const{n:o,p:s}=n,i=Ge(1-s),a=new fe(pe(n.seed),"order-dag",0);for(let c=e;c<t;c++)a.reset(c),Cs(a,s,i,c,c+1,o,r)}function X$(n){const{n:e,p:t}=n;G("n",e,0),rt("p",t),pe(n.seed);const r=xs(e*(e-1)/2,t);return Y$(n,0,e,r),oe(ae(e,r,!0),n)}function Q$(n,e,t,r){const{n:o,p:s}=n,i=Ge(1-s);if(n.directed===!0){J$(o,s,i,pe(n.seed),e,t,r);return}const a=new fe(pe(n.seed),"gnp",0);for(let c=e;c<t;c++)a.reset(c),Cs(a,s,i,c,c+1,o,r)}function J$(n,e,t,r,o,s,i){if(e===0)return;const a=new fe(r,"gnp-directed",0);for(let c=o;c<s;c++){a.reset(c);let l=e===1?0:a.nextSkip(t);for(;l<n-1;)i.push(c,l<c?l:l+1),l+=e===1?1:1+a.nextSkip(t)}}function Z$(n){const{n:e,p:t}=n;G("n",e,0),rt("p",t),pe(n.seed);const r=n.directed===!0,o=e*(e-1)/(r?1:2),s=xs(o,t);return Q$(n,0,e,s),oe(ae(e,s,r),n)}class eR{constructor(e){let t=16;for(;t<e*2;)t*=2;this.slots=new Float64Array(t).fill(-1),this.mask=t-1}add(e){let t=Math.imul(e>>>0^Math.floor(e/4294967296),2654435761)&this.mask;for(;;){const r=this.slots[t];if(r===-1)return this.slots[t]=e,!0;if(r===e)return!1;t=t+1&this.mask}}}function tR(n){const{n:e,m:t}=n,r=pe(n.seed);G("n",e,0,134217728);const o=e*(e-1)/2;G("m",t,0,Math.min(o,4294967294));const s=new fe(r,"gnm",0),i=new Float64Array(t),a=new eR(t);for(let d=0,f=o-t;f<o;f++,d++){const h=s.nextBelow(f+1);a.add(h)?i[d]=h:(a.add(f),i[d]=f)}i.sort();const c=new le(t);let l=0,u=0;for(let d=0;d<t;d++){const f=i[d];for(;f>=u+(e-l-1);)u+=e-l-1,l++;c.push(l,l+1+(f-u))}return oe(ae(e,c,!1),n)}const Os=2**24;function r0(n,e){const t=n.minCapacity??1,r=n.maxCapacity??10;return G("minCapacity",t,0,Os),G("maxCapacity",r,t,Math.floor(Os/e)),{min:t,max:r}}function ea(n,e,t,r,o,s){const{src:i,dst:a}=e.finish(),c=new Uint8Array(n);return c[r]=1,c[o]=2,{directed:!0,nodeCount:n,src:i,dst:a,weights:Float32Array.from(t),nodeColumns:{...s,role:c},source:r,sink:o}}function o0(n,e,t,r,o,s){const i=e+o*r+s,a=n.length;return s+1<r&&n.push(i,i+1),o+1<t&&n.push(i,i+r),s>0&&n.push(i,i-1),o>0&&n.push(i,i-r),n.length-a}function nR(n){const{rows:e,cols:t}=n;G("rows",e,1),G("cols",t,2);const r=e*t;G("rows * cols + 2 (the node count)",r+2,0);const{min:o,max:s}=r0(n,4),i=pe(n.seed),a=2*(e*(t-1)+t*(e-1))+2*e;Ce(a);const c=new le(a),l=[],u=new fe(i,"grid-flow",0),d=new Float64Array(r+2),f=new Float64Array(r+2);for(let w=0;w<e;w++)for(let p=0;p<t;p++){const m=w*t+p;d[m]=p,f[m]=w,u.reset(m);const y=o0(c,0,e,t,w,p);for(let b=0;b<y;b++)l.push(o+u.nextBelow(s-o+1))}const h=r,g=r+1;d[h]=-1,d[g]=t,f[h]=(e-1)/2,f[g]=(e-1)/2;for(let w=0;w<e;w++)c.push(h,w*t),l.push(4*s);for(let w=0;w<e;w++)c.push(w*t+t-1,g),l.push(4*s);return ea(r+2,c,l,h,g,{x:d,y:f})}function rR(n){const{layers:e,p:t}=n;G("layers.length",e.length,1),rt("p",t);const r=[0];let o=0;for(let l=0;l<e.length;l++)G(`layers[${l}]`,e[l],1),r.push(r[l]+e[l]),o=Math.max(o,e[l]);const s=r[e.length];G("the total size + 2 (the node count)",s+2,0);const{min:i,max:a}=r0(n,o),c=new Uint32Array(s);for(let l=0;l<e.length;l++)c.fill(l,r[l],r[l+1]);return{starts:r,layerOf:c,p:t,min:i,max:a,terminal:a*o,seed:pe(n.seed)}}function oR(n,e,t,r,o){const{starts:s,layerOf:i,p:a,min:c,max:l}=n,u=Ge(1-a),d=new fe(n.seed,"layered-flow",0),f=s.length-2;for(let h=e;h<t;h++){const g=i[h];if(g<f){d.reset(h);const w=r.length;Cs(d,a,u,h,s[g+1],s[g+2],r);for(let p=w;p<r.length;p++)o.push(c+d.nextBelow(l-c+1))}}}function sR(n){const e=rR(n),{starts:t}=e,r=t.length-1,o=t[r],s=new le(o),i=[];oR(e,0,o,s,i);const a=o,c=o+1,{terminal:l}=e;for(let d=t[0];d<t[1];d++)s.push(a,d),i.push(l);for(let d=t[r-1];d<t[r];d++)s.push(d,c),i.push(l);const u=new Uint32Array(o+2);for(let d=0;d<o;d++)u[d]=e.layerOf[d]+1;return u[c]=r+1,ea(o+2,s,i,a,c,{layer:u})}function iR(n){const{a:e,b:t,c1:r,c2:o}=n;G("a",e,1),G("b",t,1);const s=e*e;if(G("a * a * b (the node count)",s*t,2),G("c1",r,0,Os),G("c2",o,r,Os),o*s>Os)throw new RangeError(`c2 * a * a must be at most 2^24 to stay exact, got ${o*s}`);const i=pe(n.seed),a=s*t,c=t*4*e*(e-1)+(t-1)*s;Ce(c);const l=new le(c),u=[],d=new Uint32Array(a),f=new Uint32Array(s),h=new fe(i,"genrmf",0);for(let g=0;g<t;g++){const w=g*s;if(d.fill(g,w,w+s),aR(l,u,w,e,o*s),g===t-1)break;h.reset(g),cR(h,f,l,u,w,r,o)}return ea(a,l,u,0,a-1,{frame:d})}function aR(n,e,t,r,o){for(let s=0;s<r;s++)for(let i=0;i<r;i++){const a=o0(n,t,r,r,s,i);for(let c=0;c<a;c++)e.push(o)}}function cR(n,e,t,r,o,s,i){const a=e.length;for(let c=0;c<a;c++)e[c]=c;for(let c=a-1;c>0;c--){const l=n.nextBelow(c+1),u=e[c];e[c]=e[l],e[l]=u}for(let c=0;c<a;c++)t.push(o+c,o+a+e[c]),r.push(s+n.nextBelow(i-s+1))}const ta=1e6;function lR(n){const{k:e}=n;G("k",e,1,499998);const t=4*e+6,r=new le(6*e+7),o=[],s=(l,u,d)=>{r.push(l,u),o.push(d)},i=e+3,a=2*e+3,c=2*e+4;for(let l=0;l<e;l++)s(2+l,3+l,e+1-l),s(2+l,i,1);s(2+e,a,1),s(2+e,i,1);for(let l=i;l<a;l++)s(l,l+1,e+1);for(let l=0;l<=2*e;l++)s(c+l,c+l+1,e);for(let l=0;l<e;l++)s(c+l,c+2*e+1-l,1);return s(0,2,ta),s(0,c,ta),s(a,1,ta),s(c+2*e+1,1,ta),ea(t,r,o,0,1,{})}const uR=Math.SQRT2,s0=5e8;function i0(n){const e=n??2;if(e!==2&&e!==3)throw new RangeError(`dimension must be 2 or 3, got ${String(e)}`);return e}function uu(n,e,t=!1){if(!(Number.isFinite(e)&&(t?e>0:e>=0)))throw new RangeError(`${n} must be a finite number ${t?">":">="} 0, got ${String(e)}`)}function na(n,e,t,r){const o=Array.from({length:r},()=>new Float64Array(t)),s=new fe(n,e,0);for(let i=0;i<t;i++){s.reset(i);for(const a of o)a[i]=s.nextFloat()}return o}function du(n){const e=["x","y","z"];return Object.fromEntries(n.map((t,r)=>[e[r],t]))}function a0(n,e){let t=1;for(;(t+1)**e<=n;)t++;return t}function c0(n,e,t,r){const o=n[0].length,s=t.map((d,f)=>(r[f]-d)/e||1),i=n.map(()=>new Uint32Array(o)),a=new Uint32Array(o),c=new Uint32Array(e**n.length+1);for(let d=0;d<o;d++){let f=0;for(let h=0;h<n.length;h++){const g=Math.min(e-1,Math.floor((n[h][d]-t[h])/s[h]));i[h][d]=g,f=f*e+g}a[d]=f,c[f+1]++}for(let d=0;d+1<c.length;d++)c[d+1]+=c[d];const l=c.slice(0,-1),u=new Uint32Array(o);for(let d=0;d<o;d++)u[l[a[d]]++]=d;return{g:e,lo:t,side:s,start:c,items:u,cell:i}}function dR(n){const{n:e,radius:t}=n;G("n",e,0),uu("radius",t);const r=i0(n.dimension),o=n.periodic??!1,s=pe(n.seed),i=na(s,"rgg-points",e,r),a=t*t,c=Math.max(1,Math.min(Math.floor((1-1e-9)/t),a0(Math.max(1,e),r))),l=c0(i,c,new Array(r).fill(0),new Array(r).fill(1)),u=r===2?Math.PI*a:4/3*Math.PI*a*t,d=e*(e-1)/2,f=new le(Math.ceil(Math.min(d,d*u*1.1,1<<24)+16)),h={axes:i,grid:l,periodic:o,r2:a,around:hR(c,o),found:new fR};for(let g=0;g<e;g++)for(const w of gR(h,g))f.push(g,w);return oe(ae(e,f,!1,du(i)),n)}class fR{constructor(){this.data=new Uint32Array(16),this.count=0}push(e){if(this.count===this.data.length){const t=new Uint32Array(this.count*2);t.set(this.data),this.data=t}this.data[this.count++]=e}}function hR(n,e){return Array.from({length:n},(t,r)=>{const o=e?[(r+n-1)%n,r,(r+1)%n]:[r-1,r,r+1].filter(s=>s>=0&&s<n);return[...new Set(o)]})}function gR(n,e){const{grid:t,around:r,found:o}=n,{g:s,cell:i}=t,a=i.length===3;o.count=0;const c=a?r[i[2][e]]:[0];for(const l of r[i[0][e]])for(const u of r[i[1][e]])for(const d of c)wR(n,e,a?(l*s+u)*s+d:l*s+u);return o.data.subarray(0,o.count).sort()}function wR(n,e,t){const{axes:r,grid:o,periodic:s,r2:i,found:a}=n;for(let c=o.start[t];c<o.start[t+1];c++){const l=o.items[c];if(l<=e)continue;let u=0;for(const d of r){let f=Math.abs(d[e]-d[l]);s&&f>.5&&(f=1-f),u+=f*f}u<=i&&a.push(l)}}function pR(n){const{n:e,alpha:t,beta:r}=n;G("n",e,0),uu("alpha",t,!0),rt("beta",r);const o=pe(n.seed);if(r*e*e/2>s0)throw new RangeError(`waxmanGraph: beta n^2 / 2 = ${r*e*e/2} candidate pairs, above the limit of ${s0}`);const[s,i]=na(o,"waxman-points",e,2);return{n:e,seed:o,beta:r,logQ:Ge(1-r),scale:t*uR,x:s,y:i}}const l0=1e-9;function mR(n,e,t){if(t>=1e-100&&t<=1e100){const o=t*(1-e)/Math.sqrt(e);if(n>o*o*(1+l0))return!1;const s=2*t*(1-e)/(1+e);if(n<s*s*(1-l0))return!0}const r=t*Ge(e);return n<r*r}function yR(n,e,t,r){const{n:o,beta:s,logQ:i,scale:a,x:c,y:l}=n;if(s===0)return;const u=new fe(n.seed,"waxman",0),d=()=>s===1?0:u.nextSkip(i);for(let f=e;f<t;f++){u.reset(f);for(let h=f+1+d();h<o;h+=1+d()){const g=c[f]-c[h],w=l[f]-l[h];mR(g*g+w*w,u.nextFloat(),a)&&r.push(f,h)}}}function bR(n){const e=pR(n),t=new le(Math.min(Math.ceil(e.beta*e.n*e.n/8),1<<24)+16);return yR(e,0,e.n,t),oe(ae(e.n,t,!1,du([e.x,e.y])),n)}function vR(n,e,t,r,o){const s=na(n,"knn-centres",r,t),i=Array.from({length:t},()=>new Float64Array(e)),a=new Uint32Array(e),c=new fe(n,"knn-points",0),l=new Float64Array(4);for(let u=0;u<e;u++){c.reset(u);const d=c.nextBelow(r);a[u]=d;for(let f=0;f<t;f+=2){let h,g,w;do h=2*c.nextFloat()-1,g=2*c.nextFloat()-1,w=h*h+g*g;while(w>=1||w===0);const p=Math.sqrt(-2*Ge(w)/w);l[f]=h*p,l[f+1]=g*p}for(let f=0;f<t;f++)i[f][u]=s[f][d]+o*l[f]}return{axes:i,community:a}}function AR(n,e){const t=n[0].length,r=n.length;if(e===0)return new Uint32Array(0);const o=new Uint32Array(t*e),s=n.map(l=>l.reduce((u,d)=>Math.min(u,d),1/0)),i=n.map(l=>l.reduce((u,d)=>Math.max(u,d),-1/0)),a=a0(Math.max(1,t/e),r),c={axes:n,grid:c0(n,a,s,i),best:new ER(e),slack:1e-12*Math.max(1,...s.map(Math.abs),...i.map(Math.abs)),cell:new Array(r).fill(0),offset:new Array(r).fill(0)};for(let l=0;l<t;l++){_R(c,l);const u=o.subarray(l*e,(l+1)*e);u.set(c.best.index),u.sort()}return o}class ER{constructor(e){this.k=e,this.count=0,this.d2=new Float64Array(e),this.index=new Uint32Array(e)}consider(e,t){const{k:r,d2:o,index:s}=this;if(this.count===r&&(e>o[r-1]||e===o[r-1]&&t>s[r-1]))return;let i=this.count<r?this.count++:r-1;for(;i>0&&(o[i-1]>e||o[i-1]===e&&s[i-1]>t);)o[i]=o[i-1],s[i]=s[i-1],i--;o[i]=e,s[i]=t}}function _R(n,e){const{grid:t,cell:r}=n;for(let o=0;o<r.length;o++)r[o]=t.cell[o][e];n.best.count=0;for(let o=0;;o++)if(kR(n,e,o),IR(r,o,t.g)||CR(n,e,o))return}function IR(n,e,t){return n.every(r=>r-e<=0&&r+e>=t-1)}function kR(n,e,t){const{cell:r,offset:o,grid:s}=n;o.fill(-t);do{const i=PR(r,o,s.g,t);i>=0&&SR(n,e,i)}while(xR(o,t))}function SR(n,e,t){const{axes:r,grid:o,best:s}=n;for(let i=o.start[t];i<o.start[t+1];i++){const a=o.items[i];if(a!==e){let c=0;for(const l of r){const u=Math.abs(l[e]-l[a]);c+=u*u}s.consider(c,a)}}}function PR(n,e,t,r){let o=0,s=!0,i=0;for(let a=0;a<n.length;a++){const c=n[a]+e[a];(c<0||c>=t)&&(s=!1),o=Math.max(o,Math.abs(e[a])),i=i*t+c}return s&&o===r?i:-1}function xR(n,e){let t=n.length-1;for(;t>=0&&n[t]===e;)n[t]=-e,t--;return t<0?!1:(n[t]++,!0)}function CR(n,e,t){const{axes:r,grid:o,best:s,cell:i,slack:a}=n;if(s.count!==s.k)return!1;let c=1/0;for(let l=0;l<i.length;l++){const u=r[l][e]-o.lo[l];c=Math.min(c,u-(i[l]-t)*o.side[l],(i[l]+t+1)*o.side[l]-u)}return c-=a,c>0&&s.d2[s.k-1]<c*c*.999999999}function NR(n){const{n:e,k:t,clusters:r,spread:o}=n;G("n",e,0),G("k",t,0,Math.max(0,e-1));const s=i0(n.dimension),i=n.directed??!0;if(r===void 0&&o!==void 0)throw new RangeError("spread needs clusters");const a=pe(n.seed);let c;const l={};if(r===void 0)c=na(a,"knn-points",e,s);else{G("clusters",r,1);const f=o??.05;uu("spread",f);let h;({axes:c,community:h}=vR(a,e,s,r,f)),l.community=h}Object.assign(l,du(c));const u=AR(c,t);Ce(e*t);let d;if(i){d=new le(e*t);for(let f=0;f<e;f++)for(let h=f*t;h<(f+1)*t;h++)d.push(f,u[h])}else{const f=new Uint32Array(e+1);for(let w=0;w<e;w++)for(let p=w*t;p<(w+1)*t;p++)f[Math.min(w,u[p])+1]++;for(let w=0;w<e;w++)f[w+1]+=f[w];const h=f.slice(0,-1),g=new Uint32Array(e*t);for(let w=0;w<e;w++)for(let p=w*t;p<(w+1)*t;p++){const m=u[p];g[h[Math.min(w,m)]++]=Math.max(w,m)}d=new le(e*t);for(let w=0;w<e;w++){const p=g.subarray(f[w],f[w+1]).sort();for(let m=0;m<p.length;m++)(m===0||p[m]!==p[m-1])&&d.push(w,p[m])}}return oe(ae(e,d,i,l),n)}function TR(n){const{n:e}=n;G("n",e,1);const t=new fe(pe(n.seed),"recursive-tree",0),r=new Uint32Array(e-1),o=new Uint32Array(e-1);for(let s=1;s<e;s++)r[s-1]=t.nextBelow(s),o[s-1]=s;return oe({directed:!1,nodeCount:e,src:r,dst:o},n)}function OR(n,e,t){for(let r=0;r<t;r++){const o=r+n.nextBelow(e.length-r),s=e[r];e[r]=e[o],e[o]=s}}function $R(n,e){if(!(n>=0&&n<1))throw new RangeError(`forward must be a probability in [0, 1), got ${String(n)}`);if(!(e>=0&&e*n<1))throw new RangeError(`backward must be >= 0 with backward * forward < 1, got ${String(e)}`)}function RR(n){const{n:e,forward:t,backward:r}=n,o=n.maxBurn??1e3;G("n",e,1),$R(t,r),G("maxBurn",o,1);const s=new fe(pe(n.seed),"forest-fire",0),i=r*t,a=Ge(t),c=Ge(i),l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]),d=new Uint32Array(e),f=new le(4*e),h=[],g=(w,p,m)=>{const y=p.filter(v=>d[v]!==w),b=Math.min(m,y.length,o-h.length);OR(s,y,b);for(let v=0;v<b;v++)d[y[v]]=w,h.push(y[v])};for(let w=1;w<e;w++){h.length=0;const p=s.nextBelow(w);d[p]=w,h.push(p);for(let m=0;m<h.length&&h.length<o;m++){const y=h[m],b=t===0?0:s.nextSkip(a),v=i===0?0:s.nextSkip(c);g(w,l[y],b),g(w,u[y],v)}for(const m of h)f.push(w,m),l[w].push(m),u[m].push(w)}return oe(ae(e,f,!0),n)}function DR(n){const{n:e,retention:t}=n;if(G("n",e,2),!(t>0&&t<=1))throw new RangeError(`retention must be a probability in (0, 1], got ${String(t)}`);const r=new fe(pe(n.seed),"duplication-divergence",0),o=Array.from({length:e},()=>[]),s=new le(4*e);s.push(0,1),o[0].push(1),o[1].push(0);const i=1e3*e;let a=0;for(let c=2;c<e;){if(++a>i)throw new RangeError(`duplicationDivergenceGraph gave up after ${i} attempts at ${c} of ${e} nodes: retention ${t} is too small`);const l=o[r.nextBelow(c)];for(const u of l)r.nextFloat()<t&&(s.push(c,u),o[c].push(u));for(const u of o[c])o[u].push(c);o[c].length>0&&c++}return oe(ae(e,s,!1),n)}function LR(n){const{n:e,k:t,p:r}=n;if(G("k",t,2),t%2!==0)throw new RangeError(`k must be even, got ${t}`);G("n",e,t+1),rt("p",r);const o=t/2,s=e*o;Ce(2*s);const i=new le(s+Math.ceil(s*r+6*Math.sqrt(s)+16)),a=new Uint32Array(e).fill(t),c=new Set,l=(d,f)=>d<f?d*e+f:f*e+d;for(let d=0;d<e;d++)for(let f=1;f<=o;f++){const h=(d+f)%e;i.push(d,h),c.add(l(d,h))}const u=new fe(pe(n.seed),"newman-watts",0);for(let d=0;d<s;d++){const f=i.src[d];if(u.nextFloat()>=r||a[f]>=e-1)continue;let h=u.nextBelow(e);for(;h===f||c.has(l(f,h));)h=u.nextBelow(e);i.push(f,h),c.add(l(f,h)),a[f]++,a[h]++}return oe(ae(e,i,!1),n)}function MR(n){const{n:e,m:t}=n;G("m",t,1),G("n",e,t+1);const r=pe(n.seed);Ce(t*(t+1)/2+(e-t-1)*t);const o=new Float64Array(e);if(n.fitness===void 0){const w=new fe(r,"fitness",0);for(let p=0;p<e;p++)w.reset(p),o[p]=1-w.nextFloat()}else{if(n.fitness.length!==e)throw new RangeError(`fitness must have n = ${e} values, got ${n.fitness.length}`);for(let w=0;w<e;w++){const p=n.fitness[w];if(!(p>0&&Number.isFinite(p)))throw new RangeError(`fitness[${w}] must be finite and positive, got ${String(p)}`);o[w]=p}}const s=new le(t*(t+1)/2+(e-t-1)*t),i=new Uint32Array(e);for(let w=0;w<=t;w++){for(let p=w+1;p<=t;p++)s.push(w,p);i[w]=t}const a=new Float64Array(e),c=new Float64Array(e+1),l=(w,p)=>{a[w]+=p;for(let m=w+1;m<=e;m+=m&-m)c[m]+=p};let u=1;for(;u*2<=e;)u*=2;const d=(w,p)=>{let m=0,y=w;for(let b=u;b>=1;b=Math.floor(b/2))m+b<=e&&c[m+b]<=y&&(m+=b,y-=c[m]);for(m=Math.min(m,p-1);a[m]===0;)m--;return m};let f=0;for(let w=0;w<=t;w++)l(w,o[w]*t),f+=o[w]*t;const h=new fe(r,"bianconi-barabasi",0),g=new Uint32Array(t);for(let w=t+1;w<e;w++){let p=f;for(let m=0;m<t;m++){const y=d(h.nextFloat()*p,w);g[m]=y,p-=a[y],l(y,-a[y])}for(let m=0;m<t;m++){const y=g[m];s.push(w,y),i[y]++,l(y,o[y]*i[y])}i[w]=t,l(w,o[w]*t),f=0;for(let m=e;m>0;m-=m&-m)f+=c[m]}return oe(ae(e,s,!1,{fitness:o}),n)}function UR(n){const{n:e}=n;G("n",e,3);const t=3*e-6;Ce(t);const r=new fe(pe(n.seed),"apollonian",0),o=2*e-5,s=new Uint32Array(o),i=new Uint32Array(o),a=new Uint32Array(o);s[0]=0,i[0]=1,a[0]=2;let c=1;const l=new Uint32Array(t),u=new Uint32Array(t);l.set([0,0,1]),u.set([1,2,2]);let d=3;for(let f=3;f<e;f++){const h=r.nextBelow(c),g=s[h],w=i[h],p=a[h];l.fill(f,d,d+3),u[d++]=g,u[d++]=w,u[d++]=p,a[h]=f,s[c]=w,i[c]=p,a[c++]=f,s[c]=g,i[c]=p,a[c++]=f}return oe({directed:!1,nodeCount:e,src:l,dst:u},n)}function FR(n,e,t,r){const o=Math.floor(n/t),s=n-o*t;let i=0;return s>0&&(r[i++]=n-1),s+1<t&&(r[i++]=n+1),o>0&&(r[i++]=n-t),o+1<e&&(r[i++]=n+t),i}function BR(n){const{rows:e,cols:t}=n;G("rows",e,1),G("cols",t,1);const r=e*t;G("rows * cols",r,1);const o=new fe(pe(n.seed),"wilson",0),s=new Uint8Array(r),i=new Uint32Array(r),a=new Uint32Array(r-1),c=new Uint32Array(r-1),l=new Uint32Array(4);s[0]=1;let u=0;for(let h=1;h<r;h++){let g=h;for(;s[g]===0;){const w=FR(g,e,t,l);i[g]=l[o.nextBelow(w)],g=i[g]}for(g=h;s[g]===0;g=i[g])s[g]=1,a[u]=g,c[u++]=i[g]}const d=new Float64Array(r),f=new Float64Array(r);for(let h=0;h<r;h++)f[h]=Math.floor(h/t),d[h]=h-f[h]*t;return oe({directed:!1,nodeCount:r,src:a,dst:c,nodeColumns:{x:d,y:f}},n)}const u0=.7853981633974483,zR=-.16666666666666632,GR=.00833333333332249,WR=-.0001984126982985795,VR=27557313707070068e-22,jR=-25050760253406863e-24,qR=158969099521155e-24,HR=.0416666666666666,KR=-.001388888888887411,YR=2480158728947673e-20,XR=-27557314351390663e-23,QR=2087572321298175e-24,JR=-11359647557788195e-27;function d0(n){const e=n*n,t=GR+e*(WR+e*(VR+e*(jR+e*qR)));return n+e*n*(zR+e*t)}function f0(n){const e=n*n,t=e*e,r=e*(HR+e*(KR+e*YR))+t*t*(XR+e*(QR+e*JR)),o=.5*e,s=1-o;return s+(1-s-o+e*r)}function h0(n,e){const t=n*8,r=Math.floor(t),o=(t-r)*u0,s=(r&1)===1,i=s?u0-o:o,a=s?d0(i):f0(i),c=s?f0(i):d0(i);switch(r>>1&3){case 0:e[0]=a,e[1]=c;break;case 1:e[0]=-c,e[1]=a;break;case 2:e[0]=-a,e[1]=-c;break;default:e[0]=c,e[1]=-a}}const ZR=2e4;function g0(n){return(Qr(n)+Qr(-n))/2}function w0(n){return Ge(n+Math.sqrt((n-1)*(n+1)))}function eD(n){const{n:e,averageDegree:t,exponent:r}=n,o=n.temperature??0;if(G("n",e,0,ZR),!(Number.isFinite(t)&&t>0))throw new RangeError(`averageDegree must be a finite number > 0, got ${String(t)}`);if(!(Number.isFinite(r)&&r>2))throw new RangeError(`exponent must be a finite number > 2, got ${String(r)}`);if(!(o>=0&&o<1))throw new RangeError(`temperature must be in [0, 1), got ${String(o)}`);const s=pe(n.seed),i=(r-1)/2,a=i/(i-.5);let c=1;if(o>0){const A=new Float64Array(2);h0(o/2,A),c=Math.PI*o/A[1]}const l=2*a*a*e/(Math.PI*t)*c;if(e>=2&&!(l>1))throw new RangeError(`averageDegree ${t} is too large for n = ${e}: the disk radius would be <= 0`);const u=e>=2?2*Ge(l):0,d=g0(i*u);if(!Number.isFinite(d))throw new RangeError(`exponent ${r} is too large: cosh(alpha R) overflows`);const f=new Float64Array(e),h=new Float64Array(e),g=new Float64Array(e),w=new Float64Array(e),p=new Float64Array(e),m=new Float64Array(e),y=new Float64Array(e),b=new Float64Array(2),v=new fe(s,"hyperbolic-points",0);for(let A=0;A<e;A++){v.reset(A),h0(v.nextFloat(),b);const E=w0(1+(d-1)*v.nextFloat())/i,I=Qr(E);f[A]=b[0],h[A]=b[1],g[A]=(I+1/I)/2,w[A]=(I-1/I)/2,y[A]=E,p[A]=E*b[0],m[A]=E*b[1]}return{n:e,seed:s,temperature:o,R:u,coshR:g0(u),cosT:f,sinT:h,coshr:g,sinhr:w,x:p,y:m,radius:y}}function tD(n,e,t,r){const{n:o,R:s,coshR:i,temperature:a,cosT:c,sinT:l,coshr:u,sinhr:d}=n,f=new fe(n.seed,"hyperbolic",0);for(let h=e;h<t;h++){f.reset(h);for(let g=h+1;g<o;g++){const w=u[h]*u[g]-d[h]*d[g]*(c[h]*c[g]+l[h]*l[g]);if(a===0){w<i&&r.push(h,g);continue}const p=f.nextFloat();w0(Math.max(1,w))<s+2*a*Ge((1-p)/p)&&r.push(h,g)}}}function nD(n){const e=eD(n),t=new le(Math.ceil(e.n*n.averageDegree*.75)+16);return tD(e,0,e.n,t),oe(ae(e.n,t,!1,{x:e.x,y:e.y,radius:e.radius}),n)}function rD(n){const e=[[1,0,0],[0,1,0],[0,0,1]];if(!n)return e;for(let t=0;t<=1;t++)for(let r=-1;r<=1;r++)for(let o=-1;o<=1;o++){const s=Math.abs(o)+Math.abs(r)+Math.abs(t)===1;oD(t,r,o)&&!s&&e.push([o,r,t])}return e}function oD(n,e,t){return n!==0?n>0:e===0?t>0:e>0}function sD(n,e){if(n.obstacles===void 0)return null;const t=n.obstacles;if(rt("obstacles",t),t>=1)throw new RangeError("obstacles must be below 1");const r=new Uint8Array(e),o=new fe(pe(n.seed),"grid-obstacles",0);for(let s=0;s<e;s++)o.reset(s),r[s]=o.nextFloat()<t?1:0;return r}function iD(n,e,t,r){const{sizes:o,wraps:s}=n;for(let i=0;i<3;i++){let a=e[i]+t[i];if(a<0||a>=o[i]){if(!s[i])return-1;a=(a+o[i])%o[i]}r[i]=a}return r[2]*n.plane+r[1]*o[0]+r[0]}function aD(n,e,t,r,o){const{blocked:s}=e;for(const i of e.offsets){const a=iD(e,r,i,o);a>=0&&s?.[a]!==1&&n.push(t,a)}}function cD(n){const[e,t,r]=n.sizes,{plane:o,blocked:s}=n,i=new le(o*r*Math.min(n.offsets.length,3)),a=[0,0,0];for(let c=0;c<r;c++)for(let l=0;l<t;l++)for(let u=0;u<e;u++){const d=c*o+l*e+u;s?.[d]!==1&&aD(i,n,d,[u,l,c],a)}return i}function lD(n,e,t){const r=n*e*t,o=n*e,s=new Float64Array(r),i=new Float64Array(r),a=t>1?new Float64Array(r):null;for(let c=0;c<r;c++)s[c]=c%e,i[c]=Math.floor(c/e)%n,a!==null&&(a[c]=Math.floor(c/o));return a===null?{x:s,y:i}:{x:s,y:i,z:a}}function p0(n){const{rows:e,cols:t,layers:r}=n;G("rows",e,1),G("cols",t,1),G("layers",r,1);const o=e*t*r;G("rows * cols * layers",o,1);const s=n.periodic===!0,i=n.directed===!0;if(s&&i)throw new RangeError("directed grids cannot be periodic: the wrap-around arcs would close cycles");const a=rD(n.diagonals===!0);Ce(o*a.length);const c=sD(n,o),l=[t,e,r],u=l.map(g=>s&&g>=3),d=cD({sizes:l,wraps:u,plane:e*t,offsets:a,blocked:c}),f={};c!==null&&(f.blocked=c),n.positions===!0&&Object.assign(f,lD(e,t,r));const h=ae(o,d,i,Object.keys(f).length>0?f:void 0);return oe(h,n)}function uD(n){return p0({...n,layers:1})}const m0=.8660254037844386;function y0(n){G("rows",n.rows,1),G("cols",n.cols,1);const e=n.rows*n.cols;return G("rows * cols",e,1),Ce(3*e),e}function dD(n,e){const t=new Float64Array(n),r=new Float64Array(n);for(let o=0;o<n;o++){const s=Math.floor(o/e);t[o]=o%e+s/2,r[o]=s*m0}return{x:t,y:r}}function fD(n,e){const t=new Float64Array(n),r=new Float64Array(n);for(let o=0;o<n;o++){const s=Math.floor(o/e),i=o%e;t[o]=i*m0,r[o]=1.5*s+((s+i)%2===0?.5:0)}return{x:t,y:r}}function hD(n){const e=y0(n),{rows:t,cols:r}=n,o=new le(3*e);for(let i=0;i<t;i++)for(let a=0;a<r;a++){const c=i*r+a;a+1<r&&o.push(c,c+1),i+1<t&&(o.push(c,c+r),a>0&&o.push(c,c+r-1))}const s=n.positions===!0?dD(e,r):void 0;return oe(ae(e,o,!1,s),n)}function gD(n){const e=y0(n),{rows:t,cols:r}=n,o=new le(2*e);for(let i=0;i<t;i++)for(let a=0;a<r;a++){const c=i*r+a;a+1<r&&o.push(c,c+1),i+1<t&&(i+a)%2===0&&o.push(c,c+r)}const s=n.positions===!0?fD(e,r):void 0;return oe(ae(e,o,!1,s),n)}const wD=1e6;function pD(n,e,t,r,o){if(Math.ceil(n/t)*e>n)throw new RangeError(`there is no partition of ${n} nodes into communities of ${e} to ${t} nodes`);const s=new fe(o,"lfr-sizes",0),i=[];let a=-n;for(;a<0;){const c=r(s);i.push(c),a+=c}i.length*e>n&&(a-=i[i.length-1],i.pop());for(let c=i.length-1;c>=0&&a!==0;c--){const l=a>0?-Math.min(a,i[c]-e):Math.min(-a,t-i[c]);i[c]+=l,a+=l}return i}function mD(n,e,t){const r=n.length,o=Uint32Array.from({length:r},(d,f)=>f).sort((d,f)=>n[f]-n[d]||d-f),s=Uint32Array.from(e,(d,f)=>f).sort((d,f)=>e[f]-e[d]||d-f),i=e.slice(),a=[],c=new Uint32Array(r),l=new fe(t,"lfr-assign",0);let u=0;for(const d of o){for(;u<s.length&&e[s[u]]>n[d];)a.push(s[u++]);if(a.length===0)throw new RangeError(`could not assign communities: node ${d} needs a community of more than ${n[d]} nodes; raise maxCommunity or mixing, or lower maxDegree`);const f=l.nextBelow(a.length),h=a[f];c[d]=h,--i[h]===0&&(a[f]=a[a.length-1],a.pop())}return c}function yD(n){const{n:e,minDegree:t,maxDegree:r,minCommunity:o,maxCommunity:s,mixing:i}=n,a=pe(n.seed);G("n",e,1,wD),G("maxDegree",r,1,e-1),rt("mixing",i),G("maxCommunity",s,1,e);const c=Xm(["degreeExponent","minDegree","maxDegree"],n.degreeExponent,t,r),l=Xm(["communityExponent","minCommunity","maxCommunity"],n.communityExponent,o,s),u=new Uint32Array(e),d=new fe(a,"lfr-degrees",0);for(let k=0;k<e;k++)u[k]=c(d);O$(u,t,r);const f=pD(e,o,s,l,a),h=Uint32Array.from(u,k=>Math.round((1-i)*k)),g=mD(h,f,a),w=new Uint32Array(f.length+1);for(let k=0;k<f.length;k++)w[k+1]=w[k]+f[k];const p=w.slice(0,f.length),m=new Uint32Array(e);for(let k=0;k<e;k++)m[p[g[k]]++]=k;let y=0;for(const k of u)y+=k;const b=new le(y/2),v=new fe(a,"lfr-internal",0);for(let k=0;k<f.length;k++){const N=m.subarray(w[k],w[k+1]),C=Uint32Array.from(N,L=>h[L]);let O=0,T=0;for(let L=0;L<C.length;L++)O+=C[L],C[L]>C[T]&&(T=L);O%2===1&&(C[T]--,h[N[T]]--,O--);const $=lr(C,O);for(let L=0;L<$.length;L++)$[L]=N[$[L]];v.reset(k),Oo($,v),cu(e,$,!1,!1,b)}const A=Uint32Array.from(u,(k,N)=>k-h[N]);let E=0;for(const k of A)E+=k;const I=lr(A,E);return Oo(I,new fe(a,"lfr-external",0)),cu(e,I,!1,!1,b,g),oe(ae(e,b,!1,{community:g}),n)}function bD(n){const{n:e,m:t}=n,r=n.triadProbability??0;G("m",t,1),G("n",e,t+1),rt("triadProbability",r);const o=pe(n.seed),s=(e-t)*t;Ce(s);const i=new fe(o,"barabasi-albert",0),a=new le(s),c=new Uint32Array(t+2*s);let l=0;for(let h=0;h<t;h++)c[l++]=h;const u=r>0?Array.from({length:e},()=>[]):null,d=new Array(t),f=(h,g)=>{a.push(h,g),c[l++]=g,u!==null&&(u[h].push(g),u[g].push(h))};for(let h=t;h<e;h++){let g=0;for(;g<t;){const m=c[i.nextBelow(l)];let y=!0;for(let b=0;b<g;b++)y&&=d[b]!==m;y&&(d[g++]=m)}let w=0,p=d[w++];f(h,p);for(let m=1;m<t;m++){if(u!==null&&i.nextFloat()<r){const y=u[h],b=u[p].filter(v=>v!==h&&!y.includes(v));if(b.length>0){f(h,b[i.nextBelow(b.length)]);continue}}do p=d[w++];while(u!==null&&u[h].includes(p)&&w<t);if(u?.[h].includes(p))do p=c[i.nextBelow(l)];while(p===h||u[h].includes(p));f(h,p)}for(let m=0;m<t;m++)c[l++]=h}return oe(ae(e,a,!1),n)}function vD(n){const{n:e,k:t,beta:r}=n;if(G("k",t,2),t%2!==0)throw new RangeError(`k must be even, got ${t}`);G("n",e,t+1),rt("beta",r);const o=pe(n.seed),s=t/2,i=e*s;Ce(i);const a=new Uint32Array(i),c=new Uint32Array(i),l=new Uint32Array(e).fill(t),u=new Set,d=(h,g)=>h<g?h*e+g:g*e+h;for(let h=0;h<e;h++)for(let g=1;g<=s;g++){const w=(h+g)%e;a[h*s+g-1]=h,c[h*s+g-1]=w,u.add(d(h,w))}const f=new fe(o,"watts-strogatz",0);for(let h=1;h<=s;h++)for(let g=0;g<e;g++){if(f.nextFloat()>=r||l[g]>=e-1)continue;let w=f.nextBelow(e);for(;w===g||u.has(d(g,w));)w=f.nextBelow(e);const p=g*s+h-1,m=c[p];u.delete(d(g,m)),u.add(d(g,w)),l[m]--,l[w]++,c[p]=w}return oe({directed:!1,nodeCount:e,src:a,dst:c},n)}function AD(n){const{n:e}=n;G("n",e,1);const t=pe(n.seed),r=new le(e);if(e===1)return oe(ae(1,r,!1),n);const o=new fe(t,"prufer",0),s=new Uint32Array(e-2),i=new Uint32Array(e).fill(1);for(let l=0;l<e-2;l++)s[l]=o.nextBelow(e),i[s[l]]++;let a=0;for(;i[a]!==1;)a++;let c=a;for(let l=0;l<e-2;l++){const u=s[l];if(r.push(c,u),i[u]--,i[u]===1&&u<a)c=u;else{for(a++;i[a]!==1;)a++;c=a}}return r.push(c,e-1),oe(ae(e,r,!1),n)}function ED(n,e,t,r,o,s,i){const a=Ge(1-t),c=new fe(r,"layered-dag",0),l=n.length-2;for(let u=o;u<s;u++){const d=e[u];d<l&&(c.reset(u),Cs(c,t,a,u,n[d+1],n[d+2],i))}}function _D(n){const{layers:e,p:t}=n;G("layers.length",e.length,1),rt("p",t);const r=pe(n.seed),o=[0];let s=0;for(let l=0;l<e.length;l++)G(`layers[${l}]`,e[l],0),o.push(o[l]+e[l]),l>0&&(s+=e[l-1]*e[l]);const i=o[e.length];G("the total size",i,0);const a=new Uint32Array(i);for(let l=0;l<e.length;l++)a.fill(l,o[l],o[l+1]);const c=xs(s,t);return ED(o,a,t,r,0,i,c),oe(ae(i,c,!0,{layer:a}),n)}const b0=new Set(["id","source","target","parent","__proto__"]);function ID(n){return ArrayBuffer.isView(n)?Array.from(n):n}function kD(n){return n===0?0:-n}function SD(n,e,t,r=!1){const o=[];for(let i=0;i<n.nodeCount;i++)o.push(String(n.ids.idOf(i)));const s=r?i=>v0(i)&&!xD(i):v0;return[...CD(n,o,e,s),...ND(n,o,e,t,s)]}function v0(n){return n.meta.role!=="id"&&n.meta.role!=="parent"}const PD=new Set(["color","size","shape","thickness"]);function xD(n){const{role:e,name:t,origin:r}=n.meta;return e!==null&&PD.has(e)||t==="shape.uri"&&r?.namespace==="viz"}function A0(n,e,t){const r=new Set([...b0,...n.map(s=>s.meta.name)]),o=new Map;for(const s of n){const i=s.meta.name;if(!b0.has(i)){o.set(s,i);continue}const a=s.meta.origin?.id??null,c=a===null?i:`${i}#${a}`;let l=c;if(a===null||r.has(c)){let u=2;for(;r.has(`${c}#${u}`);)u++;l=`${c}#${u}`}r.add(l),o.set(s,l)}return o}function E0(n,e,t){const r={};for(const o of n)o.isSet(e)&&(r[t(o)]=ID(o.value(e)));return r}function CD(n,e,t,r){const o=[...n.nodes].filter(r),s=o.find(u=>u.meta.role==="position"&&u.meta.components>=2),i=o.filter(u=>u!==s),a=A0(i),c=n.nodes.byRole("parent"),l=[];for(let u=0;u<n.nodeCount;u++){const d=E0(i,u,w=>a.get(w)??w.meta.name);d.id=e[u];const f=c?.isSet(u)===!0?c.value(u):void 0;typeof f=="number"&&f!==u&&f<e.length&&(d.parent=e[f]);const h={group:"nodes",data:d},g=s?.isSet(u)===!0?s.value(u):void 0;g!==void 0&&Number.isFinite(g[0])&&Number.isFinite(g[1])&&(h.position={x:g[0],y:g[1]}),l.push(h)}return l}function ND(n,e,t,r,o){const s=[...n.edges].filter(o),i=s.some(g=>g.meta.name==="weight"),a=s.find(g=>g.meta.role==="weight"),c=A0(s),l=g=>g===a&&!i?"weight":c.get(g)??g.meta.name,u=n.edges.byRole("id"),d=new Set(e),f=new Set,h=[];for(let g=0;g<n.edgeCount;g++){const w=E0(s,g,l);a===void 0&&!i&&n.weights!==null&&(w.weight=n.weights[n.edgeToArc[g]]);const p=u?.isSet(g)===!0?TD(String(u.value(g)),d,f):void 0;p!==void 0&&(w.id=p),w.source=e[n.edgeSource(g)],w.target=e[n.edgeTarget(g)],h.push({group:"edges",data:w})}return h}function TD(n,e,t,r){if(!(e.has(n)||t.has(n)))return t.add(n),n}const fu={ak:lR,"balanced-tree":E$,"barabasi-albert":bD,barbell:y$,"bianconi-barabasi":MR,"bipartite-configuration-model":D$,caveman:v$,"chung-lu":U$,"circular-ladder":S$,complete:g$,"complete-bipartite":w$,"complete-multipartite":k$,"configuration-model":$$,"connected-caveman":A$,cycle:d$,"degree-corrected-sbm":B$,"directed-configuration-model":R$,"duplication-divergence":DR,empty:I$,"erdos-renyi":Z$,"erdos-renyi-gnm":tR,"forest-fire":RR,genrmf:iR,grid:uD,"grid-3d":p0,"grid-flow-network":nR,"hexagonal-lattice":gD,hyperbolic:nD,hypercube:p$,knn:NR,kronecker:j$,ladder:m$,"layered-flow-network":sR,lfr:yD,lollipop:b$,"mobius-ladder":P$,named:n=>{if(!Zi.includes(n.name))throw hu("named graph",n.name,Zi);return n$(n.name,n)},"newman-watts":LR,path:u$,petersen:_$,"planted-partition":l$,price:H$,"random-apollonian":UR,"random-bipartite":i$,"random-dag":_D,"random-geometric":dR,"random-order-dag":X$,"random-recursive-tree":TR,"random-regular":W$,"random-tree":AD,"ring-of-cliques":x$,rmat:q$,star:f$,"stochastic-block-model":Km,"triangular-lattice":hD,"watts-strogatz":vD,waxman:bR,wheel:h$,"wilson-maze":BR},OD=["karate","florentine-families","davis-southern-women","les-miserables","football","political-books","dolphins","contiguous-usa","knuth-miles","celegans-neural","political-blogs","openflights","yeast-perturbation","stelzl-interactome","wikipathways-senescence-autophagy","go-slim-generic"];function $D(n,e){let t=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=n.length;r++){const o=[r];for(let s=1;s<=e.length;s++)o[s]=Math.min(t[s]+1,o[s-1]+1,t[s-1]+(n[r-1]===e[s-1]?0:1));t=o}return t[e.length]}function hu(n,e,t){let r="",o=1/0;for(const i of t){const a=$D(e,i);a<o&&(r=i,o=a)}const s=o<=Math.max(2,e.length/3)?` (did you mean ${JSON.stringify(r)}?)`:"";return new RangeError(`unknown ${n} ${JSON.stringify(e)}${s}; the ${n}s are ${t.join(", ")}`)}function _0(n){const e="src"in n?sc(n):n;return{elements:SD(e),directed:e.directed}}function RD(n){const{x:e,y:t,...r}=n.nodeColumns??{};if(!ArrayBuffer.isView(e)||!ArrayBuffer.isView(t))return n;const o=e,s=t,i=new Float64Array(2*n.nodeCount);for(let a=0;a<n.nodeCount;a++)i[2*a]=o[a],i[2*a+1]=s[a];return{...n,nodeColumns:{...r,position:{data:i,decl:{dtype:"f64",components:2,role:"position"}}}}}function DD(n,e){const t=fu[n];if(t===void 0)throw hu("generator",n,Object.keys(fu));const r=g_[n]??[];for(const[i,a]of Object.entries(e??{}))if(a!==void 0&&!r.includes(i))throw new RangeError(`generator ${JSON.stringify(n)}: unknown option ${i}; the options are ${r.join(", ")}`);const o=_0(RD(t(e)));let s=0;for(const i of o.elements)i.group==="edges"&&(i.data.id=`e${String(s++)}`);return o}async function LD(n,e={}){if(e.signal?.throwIfAborted(),e.baseUrl===void 0&&!Hm.includes(n))throw hu("dataset",n,Hm);const t=await HO(n,e);e.signal?.throwIfAborted();const r=_0(t);for(const o of r.elements){const{x:s,y:i}=o.data;typeof s=="number"&&typeof i=="number"&&(o.position={x:s,y:kD(i)},delete o.data.x,delete o.data.y)}return r}const I0=Object.freeze(Object.defineProperty({__proto__:null,BUNDLED_DATASET_NAMES:OD,GENERATORS:fu,NAMED_GRAPH_NAMES:Zi,datasetElements:LD,generateElements:DD},Symbol.toStringTag,{value:"Module"}));return _w})();