@qe-libs/rena-wasm 0.1.14 → 0.1.16
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.
- package/README.md +52 -11
- package/demo/RS.csv +3825 -0
- package/dist/libena.js +1 -1
- package/dist/libena.wasm +0 -0
- package/package.json +4 -3
- package/src/index.js +146 -47
- package/src/pipeline.js +16 -4
- package/src/tensor.js +51 -33
package/dist/libena.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
async function LibENA(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import("node:module"));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["C"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("libena.wasm")}return new URL("libena.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var HEAPU8;var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}}var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var HEAP16;var HEAPU16;var HEAP32;var HEAP64;var HEAPU64;var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){var value=emval_handles[handle];emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var HEAPF32;var HEAPF64;var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function argsUseStackAlloc(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].argStackAlloc){return true}}return false}function createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync){var needsDestructorStack=usesDestructorStack(argTypes);var argsNeedStack=argsUseStackAlloc(argTypes);var useStackFrame=argsNeedStack&&!isAsync&&!needsDestructorStack;if(argsNeedStack&&!useStackFrame){needsDestructorStack=true}var argCount=argTypes.length-2;var argsList=[];var argsListWired=["fn"];if(isClassMethodFunc){argsListWired.push("thisWired")}for(var i=0;i<argCount;++i){argsList.push(`arg${i}`);argsListWired.push(`arg${i}Wired`)}argsList=argsList.join();argsListWired=argsListWired.join();var invokerFnBody=`return function (${argsList}) {\n`;if(needsDestructorStack){invokerFnBody+="var destructors = [];\n"}if(useStackFrame){invokerFnBody+="var sp = stackSave();\ntry {\n"}var dtorStack=needsDestructorStack?"destructors":"null";var args1=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];if(useStackFrame){args1.push("stackSave","stackRestore")}if(isClassMethodFunc){invokerFnBody+=`var thisWired = toClassParamWire(${dtorStack}, this);\n`}for(var i=0;i<argCount;++i){var argName=`toArg${i}Wire`;invokerFnBody+=`var arg${i}Wired = ${argName}(${dtorStack}, arg${i});\n`;args1.push(argName)}invokerFnBody+=(returns||isAsync?"var rv = ":"")+`invoker(${argsListWired});\n`;if(useStackFrame){invokerFnBody+="} finally {\nstackRestore(sp);\n}\n"}if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){var paramName=i===1?"thisWired":`arg${i-2}Wired`;if(argTypes[i].destructorFunction!==null){invokerFnBody+=`${paramName}_dtor(${paramName});\n`;args1.push(`${paramName}_dtor`)}}}if(returns){invokerFnBody+="var ret = fromRetWire(rv);\n"+"return ret;\n"}else{}invokerFnBody+="}\n";return new Function(args1,invokerFnBody)}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and receiver (this) types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var argsNeedStack=argsUseStackAlloc(argTypes);var useStackFrame=argsNeedStack&&!isAsync&&!needsDestructorStack;if(argsNeedStack&&!useStackFrame){needsDestructorStack=true}var returns=!argTypes[0].isVoid;var retType=argTypes[0];var instType=argTypes[1];var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,retType.fromWireType.bind(retType),instType?.toWireType.bind(instType)];if(useStackFrame){closureArgs.push(stackSave,stackRestore)}for(var i=2;i<argCount;++i){var argType=argTypes[i];closureArgs.push(argType.toWireType.bind(argType))}if(!needsDestructorStack){for(var i=isClassMethodFunc?1:2;i<argTypes.length;++i){if(argTypes[i].destructorFunction!==null){closureArgs.push(argTypes[i].destructorFunction)}}}let invokerFactory=createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync);var invokerFn=invokerFactory(...closureArgs);return createNamedFunction(humanName,invokerFn)}var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}}var throwInternalError=message=>{throw new InternalError(message)};var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite=2147483647)=>{if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite=2147483647)=>{if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var captures={toValue:Emval.toValue};var args=argFromPtr.map((argFromPtr,i)=>{var captureName=`argFromPtr${i}`;captures[captureName]=argFromPtr;return`${captureName}(args${i?"+"+i*GenericWireTypeSize:""})`});var functionBody;switch(kind){case 0:functionBody="toValue(handle)";break;case 2:functionBody="new (toValue(handle))";break;case 3:functionBody="";break;case 1:captures["getStringOrSymbol"]=getStringOrSymbol;functionBody="toValue(handle)[getStringOrSymbol(methodName)]";break}functionBody+=`(${args})`;if(!retType.isVoid){captures["toReturnWire"]=toReturnWire;captures["emval_returnValue"]=emval_returnValue;functionBody=`return emval_returnValue(toReturnWire, destructorsRef, ${functionBody})`}functionBody=`return function (handle, methodName, destructorsRef, args) {\n${functionBody}\n}`;var invokerFunction=new Function(Object.keys(captures),functionBody)(...Object.values(captures));var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_get_property=(handle,key)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);return Emval.toHandle(handle[key])};var __emval_incref=handle=>{if(handle>9){emval_handles[handle+1]+=1}};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_is_string=handle=>{handle=Emval.toValue(handle);return typeof handle=="string"};var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var ___getTypeName,_free,_malloc,__emscripten_stack_restore,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["D"];_free=wasmExports["E"];_malloc=wasmExports["G"];__emscripten_stack_restore=wasmExports["H"];_emscripten_stack_get_current=wasmExports["I"];memory=wasmMemory=wasmExports["B"];__indirect_function_table=wasmTable=wasmExports["F"]}var wasmImports={b:___cxa_throw,u:__abort_js,q:__embind_register_bigint,y:__embind_register_bool,w:__embind_register_emval,p:__embind_register_float,d:__embind_register_function,l:__embind_register_integer,i:__embind_register_memory_view,x:__embind_register_std_string,o:__embind_register_std_wstring,z:__embind_register_void,g:__emval_create_invoker,a:__emval_decref,m:__emval_get_property,j:__emval_incref,f:__emval_invoke,A:__emval_is_string,k:__emval_new_array,c:__emval_new_cstring,n:__emval_new_object,e:__emval_run_destructors,h:__emval_set_property,t:__tzset_js,v:_emscripten_resize_heap,r:_environ_get,s:_environ_sizes_get};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
1
|
+
async function LibENA(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import("node:module"));var require=createRequire(import.meta.url)}var thisProgram="./this.program";var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"])return Module["locateFile"](path,scriptDirectory);return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:"))scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?void 0:"utf8");return ret};if(process.argv.length>1)thisProgram=process.argv[1].replace(/\\/g,"/");process.argv.slice(2);0}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok)return response.arrayBuffer();throw new Error(response.status+" : "+response.url)}}console.log.bind(console);var err=console.error.bind(console);var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun==="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){0;wasmExports["C"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun==="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";throw new WebAssembly.RuntimeError(what)}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"])return locateFile("libena.wasm");return new URL("libena.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary)return readBinary(file);throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(true)try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE)try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0)callbacks.shift()(Module)};var onPostRuns=[];var onPreRuns=[];var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=()=>{abort()};var HEAPU8;var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}}var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType)throwBindingError(`type "${name}" must have a positive integer typeid pointer`);if(registeredTypes.hasOwnProperty(rawType))if(options.ignoreDuplicateRegistrations)return;else throwBindingError(`Cannot register type '${name}' twice`);registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var HEAP16;var HEAPU16;var HEAP32;var HEAP64;var HEAPU64;var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle];emval_handles[handle]=void 0;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle)throwBindingError(`Cannot use deleted val. handle = ${handle}`);return emval_handles[handle]},toHandle:value=>{switch(value){case void 0:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var HEAPF32;var HEAPF64;var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i)if(argTypes[i]!==null&&argTypes[i].destructorFunction===void 0)return true;return false}function argsUseStackAlloc(argTypes){for(var i=1;i<argTypes.length;++i)if(argTypes[i]!==null&&argTypes[i].argStackAlloc)return true;return false}function createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync){var needsDestructorStack=usesDestructorStack(argTypes);var argsNeedStack=argsUseStackAlloc(argTypes);var useStackFrame=argsNeedStack&&!isAsync&&!needsDestructorStack;if(argsNeedStack&&!useStackFrame)needsDestructorStack=true;var argCount=argTypes.length-2;var argsList=[];var argsListWired=["fn"];if(isClassMethodFunc)argsListWired.push("thisWired");for(var i=0;i<argCount;++i){argsList.push(`arg${i}`);argsListWired.push(`arg${i}Wired`)}argsList=argsList.join();argsListWired=argsListWired.join();var invokerFnBody=`return function (${argsList}) {\n`;if(needsDestructorStack)invokerFnBody+="var destructors = [];\n";if(useStackFrame)invokerFnBody+="var sp = stackSave();\ntry {\n";var dtorStack=needsDestructorStack?"destructors":"null";var args1=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];if(useStackFrame)args1.push("stackSave","stackRestore");if(isClassMethodFunc)invokerFnBody+=`var thisWired = toClassParamWire(${dtorStack}, this);\n`;for(i=0;i<argCount;++i){var argName=`toArg${i}Wire`;invokerFnBody+=`var arg${i}Wired = ${argName}(${dtorStack}, arg${i});\n`;args1.push(argName)}invokerFnBody+=(returns||isAsync?"var rv = ":"")+`invoker(${argsListWired});\n`;if(useStackFrame)invokerFnBody+="} finally {\nstackRestore(sp);\n}\n";if(needsDestructorStack)invokerFnBody+="runDestructors(destructors);\n";else for(i=isClassMethodFunc?1:2;i<argTypes.length;++i){var paramName=i===1?"thisWired":`arg${i-2}Wired`;if(argTypes[i].destructorFunction!==null){invokerFnBody+=`${paramName}_dtor(${paramName});\n`;args1.push(`${paramName}_dtor`)}}if(returns)invokerFnBody+="var ret = fromRetWire(rv);\nreturn ret;\n";invokerFnBody+="}\n";return new Function(args1,invokerFnBody)}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2)throwBindingError("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var argsNeedStack=argsUseStackAlloc(argTypes);var useStackFrame=argsNeedStack&&!isAsync&&!needsDestructorStack;if(argsNeedStack&&!useStackFrame)needsDestructorStack=true;var returns=!argTypes[0].isVoid;var retType=argTypes[0];var instType=argTypes[1];var closureArgs=[humanName,throwBindingError,cppInvokerFunc,cppTargetFunc,runDestructors,retType.fromWireType.bind(retType),instType?.toWireType.bind(instType)];if(useStackFrame)closureArgs.push(stackSave,stackRestore);for(var i=2;i<argCount;++i){var argType=argTypes[i];closureArgs.push(argType.toWireType.bind(argType))}if(!needsDestructorStack)for(i=isClassMethodFunc?1:2;i<argTypes.length;++i)if(argTypes[i].destructorFunction!==null)closureArgs.push(argTypes[i].destructorFunction);let invokerFactory=createJsInvoker(argTypes,isClassMethodFunc,returns,isAsync);var invokerFn=invokerFactory(...closureArgs);return createNamedFunction(humanName,invokerFn)}var ensureOverloadTable=(proto,methodName,humanName)=>{if(void 0===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length))throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`);return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(void 0===numArguments||void 0!==Module[name].overloadTable&&void 0!==Module[name].overloadTable[numArguments])throwBindingError(`Cannot register public name '${name}' twice`);ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments))throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`);Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++)array.push(HEAPU32[firstElement+i*4>>2]);return array};class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}}var throwInternalError=message=>{throw new InternalError(message)};var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name))throwInternalError("Replacing nonexistent public symbol");if(void 0!==Module[name].overloadTable&&void 0!==numArguments)Module[name].overloadTable[numArguments]=value;else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func)wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr);return func};var embind__requireFunction=(signature,rawFunction)=>{signature=AsciiToString(signature);var fp=function(){var rtn=getWasmTableEntry(rawFunction);return rtn}();if(typeof fp!=="function")throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`);return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};types.forEach(function visit(type){if(seen[type])return;if(registeredTypes[type])return;if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true});throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length)throwInternalError("Mismatched type converter count");for(var i=0;i<myTypes.length;++i)registerType(myTypes[i],myTypeConverters[i])}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries())if(registeredTypes.hasOwnProperty(dt))typeConverters[i]=registeredTypes[dt];else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt))awaitingDependencies[dt]=[];awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length)onComplete(typeConverters)})}if(0===unregisteredTypes.length)onComplete(typeConverters)};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127)len++;else if(c<=2047)len+=2;else if(c>=55296&&c<=57343){len+=4;++i}else len+=3}return len};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder)return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr));var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224)u0=(u0&15)<<12|u1<<6|u2;else u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63;if(u0<65536)str+=String.fromCharCode(u0);else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite=2147483647)=>{if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite=2147483647)=>{if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535)i++;HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535)i++;len+=4}return len};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(void 0===impl)throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i)a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`);return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length)HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors);return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===void 0)return AsciiToString(address);return symbol};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV)if(ENV[x]===void 0)delete env[x];else env[x]=ENV[x];var strings=[];for(var x in env)strings.push(`${x}=${env[x]}`);getEnvStrings.strings=strings}return getEnvStrings.strings};if(Module["noExitRuntime"])Module["noExitRuntime"];if(Module["print"])Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit==="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0)preInit.shift()()}var ___getTypeName,_free,_malloc,__emscripten_stack_restore,_emscripten_stack_get_current,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["D"];_free=wasmExports["E"];_malloc=wasmExports["G"];__emscripten_stack_restore=wasmExports["H"];_emscripten_stack_get_current=wasmExports["I"];wasmMemory=wasmExports["B"];wasmTable=wasmExports["F"]}var wasmImports={b:(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException()},u:()=>abort(""),q:(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value==="number")value=BigInt(value);return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})},y:(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})},w:rawType=>registerType(rawType,EmValType),p:(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})},d:(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})},m:(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})},i:(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})},x:(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(true)str=UTF8ToString(payload,length,true);else{str="";for(var i=0;i<length;++i)str+=String.fromCharCode(HEAPU8[payload+i])}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer)value=new Uint8Array(value);var length;var valueIsOfTypeString=typeof value==="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1))throwBindingError("Cannot pass non-string to std::string");if(true,valueIsOfTypeString)length=lengthBytesUTF8(value);else length=value.length;var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString)if(true)stringToUTF8(value,ptr,length+1);else for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}else HEAPU8.set(value,ptr);if(destructors!==null)destructors.push(_free,base);return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})},o:(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value==="string"))throwBindingError(`Cannot pass non-string to C++ string type ${name}`);var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null)destructors.push(_free,ptr);return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})},z:(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>{},toWireType:()=>{}})},h:(argCount,argTypesPtr,kind)=>{var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var captures={toValue:Emval.toValue};var args=argFromPtr.map((argFromPtr,i)=>{var captureName=`argFromPtr${i}`;captures[captureName]=argFromPtr;return`${captureName}(args${i?"+"+i*8:""})`});var functionBody;switch(kind){case 0:functionBody="toValue(handle)";break;case 2:functionBody="new (toValue(handle))";break;case 3:functionBody="";break;case 1:captures["getStringOrSymbol"]=getStringOrSymbol;functionBody="toValue(handle)[getStringOrSymbol(methodName)]";break}functionBody+=`(${args})`;if(!retType.isVoid){captures["toReturnWire"]=toReturnWire;captures["emval_returnValue"]=emval_returnValue;functionBody=`return emval_returnValue(toReturnWire, destructorsRef, ${functionBody})`}functionBody=`return function (handle, methodName, destructorsRef, args) {\n${functionBody}\n}`;var invokerFunction=new Function(Object.keys(captures),functionBody)(...Object.values(captures));var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))},a:__emval_decref,n:(handle,key)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);return Emval.toHandle(handle[key])},k:handle=>{if(handle>9)emval_handles[handle+1]+=1},g:(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args),A:handle=>{handle=Emval.toValue(handle);return typeof handle==="string"},j:()=>Emval.toHandle([]),c:v=>Emval.toHandle(getStringOrSymbol(v)),l:()=>Emval.toHandle({}),f:handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)},e:(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value},t:(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}},v:requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize)return false;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement)return true}return false},r:(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,1/0)+1;envp+=4}return 0},s:(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings)bufSize+=lengthBytesUTF8(string)+1;HEAPU32[penviron_buf_size>>2]=bufSize;return 0}};var wasmExports;wasmExports=await async function(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm)return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))});wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(void 0,wasmBinaryFile,info);var exports=function(result){return receiveInstance(result["instance"])}(result);return exports}();await async function(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}();
|
|
2
2
|
;return Module}export default LibENA;
|
package/dist/libena.wasm
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@qe-libs/rena-wasm",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "JavaScript/WebAssembly ENA pipeline
|
|
3
|
+
"version": "0.1.16",
|
|
4
|
+
"description": "JavaScript/WebAssembly ENA pipeline \u2014 libena (ENA rotations, node positions) compiled to WASM, over @qe-libs/libqe-wasm",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"files": [
|
|
8
8
|
"dist/libena.js",
|
|
9
9
|
"dist/libena.wasm",
|
|
10
|
-
"src/"
|
|
10
|
+
"src/",
|
|
11
|
+
"demo/RS.csv"
|
|
11
12
|
],
|
|
12
13
|
"scripts": {
|
|
13
14
|
"build": "sh scripts/build.sh",
|
package/src/index.js
CHANGED
|
@@ -15,6 +15,13 @@
|
|
|
15
15
|
* Top-level fields (= R's set$...):
|
|
16
16
|
* connectionCounts Float64Array (nUnits × nConnections) — raw accumulation
|
|
17
17
|
* rowConnectionCounts Float64Array (nRows × nConnections) — per-row raw accumulation
|
|
18
|
+
* selfConnectionCounts Float64Array (nUnits × nCodes) — self-connections:
|
|
19
|
+
* ground i × response i per line (the ordered diagonal),
|
|
20
|
+
* weighted per line; kept alongside, not used by the model
|
|
21
|
+
* missCounts Float64Array (nUnits × nConnections) | null — missed
|
|
22
|
+
* co-occurrences (ground i present, response j absent);
|
|
23
|
+
* opts.misses (default true)
|
|
24
|
+
* selfMissCounts Float64Array (nUnits × nCodes) | null — self-misses
|
|
18
25
|
* lineWeights Float64Array (nUnits × nConnections) — sphere-normed
|
|
19
26
|
* points Float64Array (nUnits × dims) — projected positions
|
|
20
27
|
* rotationMatrix Float64Array (nConnections × dims) — rotation vectors
|
|
@@ -113,7 +120,9 @@ function totalVariance(m, nRows, nCols) {
|
|
|
113
120
|
* Build the adjacency key — list of [codeA, codeB] pairs for each connection.
|
|
114
121
|
* Matches R's rotation$adjacency.key.
|
|
115
122
|
*
|
|
116
|
-
* Unordered: the upper triangle in column-major order (choose_two(n) pairs)
|
|
123
|
+
* Unordered: the upper triangle in column-major order (choose_two(n) pairs),
|
|
124
|
+
* or with `diagonal` including self-connections: A & A, A & B, B & B, ...
|
|
125
|
+
* (n(n+1)/2 pairs, libena's undirected_connection_key(n, true) order).
|
|
117
126
|
* Ordered: all n² directed connections in column-major order — column
|
|
118
127
|
* j*n + i is [codes[i], codes[j]], ground codes[i] → response codes[j]
|
|
119
128
|
* (as R names it "codes[i] & codes[j]").
|
|
@@ -122,7 +131,7 @@ function totalVariance(m, nRows, nCols) {
|
|
|
122
131
|
* @param {boolean} [ordered=false]
|
|
123
132
|
* @returns {string[][]} length nConnections, each entry is [codeI, codeJ]
|
|
124
133
|
*/
|
|
125
|
-
function buildAdjacencyKey(codes, ordered = false) {
|
|
134
|
+
function buildAdjacencyKey(codes, ordered = false, diagonal = false) {
|
|
126
135
|
const key = [];
|
|
127
136
|
if (ordered) {
|
|
128
137
|
for (let j = 0; j < codes.length; j++)
|
|
@@ -130,12 +139,18 @@ function buildAdjacencyKey(codes, ordered = false) {
|
|
|
130
139
|
key.push([codes[i], codes[j]]);
|
|
131
140
|
return key;
|
|
132
141
|
}
|
|
133
|
-
for (let j =
|
|
134
|
-
for (let i = 0; i < j; i++)
|
|
142
|
+
for (let j = 0; j < codes.length; j++)
|
|
143
|
+
for (let i = 0; i < (diagonal ? j + 1 : j); i++)
|
|
135
144
|
key.push([codes[i], codes[j]]);
|
|
136
145
|
return key;
|
|
137
146
|
}
|
|
138
147
|
|
|
148
|
+
// Number of connection columns for a layout.
|
|
149
|
+
function connectionCount(qe, nCodes, ordered, diagonal = false) {
|
|
150
|
+
if (ordered) return nCodes * nCodes;
|
|
151
|
+
return diagonal ? (nCodes * (nCodes + 1)) / 2 : qe.choose_two(nCodes);
|
|
152
|
+
}
|
|
153
|
+
|
|
139
154
|
/**
|
|
140
155
|
* Connection names, "codeA & codeB" per connection, in network column order
|
|
141
156
|
* (= R's colnames(set$connection.counts)).
|
|
@@ -145,9 +160,9 @@ function buildAdjacencyKey(codes, ordered = false) {
|
|
|
145
160
|
* @param {boolean} [ordered=false]
|
|
146
161
|
* @returns {string[]}
|
|
147
162
|
*/
|
|
148
|
-
function connectionNamesFor(qe, codes, ordered = false) {
|
|
149
|
-
if (!ordered) return qe.connection_names(codes);
|
|
150
|
-
return buildAdjacencyKey(codes,
|
|
163
|
+
function connectionNamesFor(qe, codes, ordered = false, diagonal = false) {
|
|
164
|
+
if (!ordered && !diagonal) return qe.connection_names(codes);
|
|
165
|
+
return buildAdjacencyKey(codes, ordered, diagonal).map(([a, b]) => `${a} & ${b}`);
|
|
151
166
|
}
|
|
152
167
|
|
|
153
168
|
// ── ENA result object ─────────────────────────────────────────────────────────
|
|
@@ -184,6 +199,9 @@ class ENAModel {
|
|
|
184
199
|
centerVec: opts.centerVec,
|
|
185
200
|
codes: opts.codes,
|
|
186
201
|
adjacencyKey: opts.adjacencyKey,
|
|
202
|
+
// ordered models: the node optimization's self-connection weight
|
|
203
|
+
// (= R's rotation$self.weight); null for unordered models
|
|
204
|
+
selfWeight: opts.selfWeight ?? null,
|
|
187
205
|
};
|
|
188
206
|
|
|
189
207
|
// ── column class annotations (mirrors R's S3 class tags) ─────────────
|
|
@@ -271,8 +289,9 @@ function weightModelName(name) {
|
|
|
271
289
|
* @param {number} nUnits
|
|
272
290
|
* @param {number} nConnections
|
|
273
291
|
* @param {boolean} ordered
|
|
292
|
+
* @param {boolean} [diagonal=false] unordered with self-connection columns
|
|
274
293
|
*/
|
|
275
|
-
function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered) {
|
|
294
|
+
function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered, diagonal = false) {
|
|
276
295
|
if (!codeMask || codeMask.length !== nCodes) return;
|
|
277
296
|
const zeroColumn = (k) => {
|
|
278
297
|
for (let u = 0; u < nUnits; u++) networks[u * nConnections + k] = 0;
|
|
@@ -284,8 +303,8 @@ function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered
|
|
|
284
303
|
return;
|
|
285
304
|
}
|
|
286
305
|
let k = 0;
|
|
287
|
-
for (let col = 1; col < nCodes; col++) {
|
|
288
|
-
for (let row = 0; row < col; row++) {
|
|
306
|
+
for (let col = diagonal ? 0 : 1; col < nCodes; col++) {
|
|
307
|
+
for (let row = 0; row < (diagonal ? col + 1 : col); row++) {
|
|
289
308
|
if ((codeMask[row] && codeMask[row][col] === 0) ||
|
|
290
309
|
(codeMask[col] && codeMask[col][row] === 0)) zeroColumn(k);
|
|
291
310
|
k++;
|
|
@@ -293,6 +312,16 @@ function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered
|
|
|
293
312
|
}
|
|
294
313
|
}
|
|
295
314
|
|
|
315
|
+
// Self vectors (nUnits × nCodes): zero a code's self-connection when the mask
|
|
316
|
+
// excludes its diagonal (codeMask[i][i] === 0), as applyCodeMask does for
|
|
317
|
+
// ordered networks' diagonal.
|
|
318
|
+
function applySelfMask(selfNetworks, codeMask, nCodes, nUnits) {
|
|
319
|
+
if (!selfNetworks || !codeMask || codeMask.length !== nCodes) return;
|
|
320
|
+
for (let i = 0; i < nCodes; i++)
|
|
321
|
+
if (codeMask[i] && codeMask[i][i] === 0)
|
|
322
|
+
for (let u = 0; u < nUnits; u++) selfNetworks[u * nCodes + i] = 0;
|
|
323
|
+
}
|
|
324
|
+
|
|
296
325
|
// ── custom rotation (= R's rotation.set) ─────────────────────────────────────
|
|
297
326
|
|
|
298
327
|
// Rows of a matrix given as an array of row arrays, or as flat row-major data
|
|
@@ -355,7 +384,8 @@ function unitCircleArgs(model, plane, mode) {
|
|
|
355
384
|
if (plane[0] === plane[1]) throw new Error(`${name}: the two dimensions must differ`);
|
|
356
385
|
const nCodes = codes.length;
|
|
357
386
|
const ordered = nConnections === nCodes * nCodes;
|
|
358
|
-
if (!ordered && nConnections !== nCodes * (nCodes - 1) / 2
|
|
387
|
+
if (!ordered && nConnections !== nCodes * (nCodes - 1) / 2 &&
|
|
388
|
+
nConnections !== nCodes * (nCodes + 1) / 2) { // with self-connection columns
|
|
359
389
|
throw new Error(`${name}: ${nConnections} connections do not fit ${nCodes} codes`);
|
|
360
390
|
}
|
|
361
391
|
checkPoints(name + ' (nodes)', nodes, nCodes, dims);
|
|
@@ -380,7 +410,7 @@ function unitCircleArgs(model, plane, mode) {
|
|
|
380
410
|
* nodes: number[][], centerVec: Float64Array,
|
|
381
411
|
* eigenvalues: number[]|null, columnNames: string[] }}
|
|
382
412
|
*/
|
|
383
|
-
function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
413
|
+
function resolveRotationSet(rs, codes, nConnections, ordered, diagonal = false) {
|
|
384
414
|
const rot = matrixRows(rs.rotationMatrix, rs.rotationCols);
|
|
385
415
|
if (!rot || rot.length !== nConnections) {
|
|
386
416
|
throw new Error(
|
|
@@ -408,8 +438,8 @@ function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
|
408
438
|
if (src.length !== codes.length || codeIdx.some(i => i < 0)) {
|
|
409
439
|
throw new Error('rotationSet.codes do not match this model\'s codes');
|
|
410
440
|
}
|
|
411
|
-
const srcKey = new Map(buildAdjacencyKey(src, ordered).map(([a, b], k) => [a + '\u0000' + b, k]));
|
|
412
|
-
connIdx = buildAdjacencyKey(codes, ordered).map(([a, b]) => {
|
|
441
|
+
const srcKey = new Map(buildAdjacencyKey(src, ordered, diagonal).map(([a, b], k) => [a + '\u0000' + b, k]));
|
|
442
|
+
connIdx = buildAdjacencyKey(codes, ordered, diagonal).map(([a, b]) => {
|
|
413
443
|
const k = srcKey.get(a + '\u0000' + b) ?? (ordered ? undefined : srcKey.get(b + '\u0000' + a));
|
|
414
444
|
if (k === undefined) throw new Error(`rotationSet has no connection '${a} & ${b}'`);
|
|
415
445
|
return k;
|
|
@@ -431,17 +461,25 @@ function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
|
431
461
|
|
|
432
462
|
// ── shared pipeline (post-accumulation) ──────────────────────────────────────
|
|
433
463
|
|
|
434
|
-
// norm: { sphereNorm = true, centerAlignToOrigin = true
|
|
435
|
-
// model(normalize =)
|
|
436
|
-
// applies to every model; centerAlignToOrigin
|
|
437
|
-
// ordered (ONA) models always centre as
|
|
464
|
+
// norm: { sphereNorm = true, centerAlignToOrigin = true, selfWeight = 2 } (=
|
|
465
|
+
// R's norm.by / model(normalize =), ena.make.set's center.align.to.origin and
|
|
466
|
+
// model(self_weight =)). sphereNorm applies to every model; centerAlignToOrigin
|
|
467
|
+
// to unordered models only -- ordered (ONA) models always centre as
|
|
468
|
+
// ona::model() does; selfWeight to node optimization (ordered models, and
|
|
469
|
+
// unordered ones with self-connection columns); selfConnections marks
|
|
470
|
+
// unordered networks that carry self-connection columns (A & A, ...).
|
|
438
471
|
function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
439
472
|
metaData, rotMethod, groupA, groupB, dims, gParams,
|
|
440
473
|
rowConnectionCounts = null, ordered = false, rotationSet = null,
|
|
441
474
|
norm = {}) {
|
|
442
|
-
|
|
475
|
+
// Unordered models with self-connection columns (accumulate's
|
|
476
|
+
// selfConnections): the key, names and node weighting include them.
|
|
477
|
+
const diagonal = !ordered && norm.selfConnections === true;
|
|
478
|
+
const key = ordered ? null : qe.undirected_connection_key(codes.length, diagonal);
|
|
479
|
+
const connectionNames = connectionNamesFor(qe, codes, ordered, diagonal);
|
|
443
480
|
const useSphereNorm = norm.sphereNorm !== false;
|
|
444
481
|
const alignToOrigin = ordered || norm.centerAlignToOrigin !== false;
|
|
482
|
+
const selfWeight = norm.selfWeight ?? 2;
|
|
445
483
|
|
|
446
484
|
// Sphere norm → lineWeights (= R's set$line.weights). Without it, every
|
|
447
485
|
// network is scaled by the largest network's length (fun_skip_sphere_norm).
|
|
@@ -466,8 +504,8 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
466
504
|
return runCustomRotation(qe, rawNetworks, lineWeights, pointsForProjection,
|
|
467
505
|
centerVec, nUnits, nConnections, codes, unitLabels,
|
|
468
506
|
metaData, dims, rowConnectionCounts, ordered,
|
|
469
|
-
resolveRotationSet(rotationSet, codes, nConnections, ordered),
|
|
470
|
-
alignToOrigin);
|
|
507
|
+
resolveRotationSet(rotationSet, codes, nConnections, ordered, diagonal),
|
|
508
|
+
alignToOrigin, selfWeight, diagonal);
|
|
471
509
|
}
|
|
472
510
|
|
|
473
511
|
// Rotate
|
|
@@ -510,7 +548,8 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
510
548
|
// Ordered (ONA) models use libqe's directed_node_positions, as
|
|
511
549
|
// ona::model() does (via rENA's optimize()).
|
|
512
550
|
const { nodes, centroids } = nodePositions(
|
|
513
|
-
qe, lineWeights, nUnits, nConnections, points, dims, ordered
|
|
551
|
+
qe, lineWeights, nUnits, nConnections, points, dims, ordered, selfWeight,
|
|
552
|
+
key, codes.length
|
|
514
553
|
);
|
|
515
554
|
|
|
516
555
|
// ONA: translate points and nodes so the points' mean is at the origin
|
|
@@ -541,7 +580,7 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
541
580
|
const variance = computeVariance(points, nUnits, dims, total);
|
|
542
581
|
|
|
543
582
|
// Adjacency key (= R's rotation$adjacency.key)
|
|
544
|
-
const adjacencyKey = buildAdjacencyKey(codes, ordered);
|
|
583
|
+
const adjacencyKey = buildAdjacencyKey(codes, ordered, diagonal);
|
|
545
584
|
|
|
546
585
|
return new ENAModel({
|
|
547
586
|
// top-level
|
|
@@ -567,12 +606,14 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
567
606
|
centerVec,
|
|
568
607
|
codes,
|
|
569
608
|
adjacencyKey,
|
|
609
|
+
selfWeight,
|
|
570
610
|
});
|
|
571
611
|
}
|
|
572
612
|
|
|
573
613
|
function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterVec,
|
|
574
614
|
nUnits, nConnections, codes, unitLabels, metaData, dims,
|
|
575
|
-
rowConnectionCounts, ordered, rs, alignToOrigin = true
|
|
615
|
+
rowConnectionCounts, ordered, rs, alignToOrigin = true,
|
|
616
|
+
selfWeight = 2, diagonal = false) {
|
|
576
617
|
let pointsForProjection = ownCentered;
|
|
577
618
|
let centerVec = ownCenterVec;
|
|
578
619
|
if (!ordered) {
|
|
@@ -609,9 +650,11 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
609
650
|
rs.nodes.forEach((row, c) => { for (let d = 0; d < dims; d++) nodes[c * dims + d] = Number(row[d]) || 0; });
|
|
610
651
|
let centroids;
|
|
611
652
|
if (ordered) {
|
|
612
|
-
centroids = nodePositions(qe, lineWeights, nUnits, nConnections, points, dims, true).centroids;
|
|
653
|
+
centroids = nodePositions(qe, lineWeights, nUnits, nConnections, points, dims, true, selfWeight).centroids;
|
|
613
654
|
} else {
|
|
614
|
-
const
|
|
655
|
+
const key = qe.undirected_connection_key(codes.length, diagonal);
|
|
656
|
+
const w = qe.node_weights_by_key(lineWeights, nUnits, nConnections, key.from, key.to,
|
|
657
|
+
codes.length, selfWeight);
|
|
615
658
|
centroids = matmul(Float64Array.from(w.data), nUnits, w.cols, nodes, dims);
|
|
616
659
|
}
|
|
617
660
|
|
|
@@ -622,7 +665,7 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
622
665
|
points,
|
|
623
666
|
rotationMatrix,
|
|
624
667
|
metaData,
|
|
625
|
-
connectionNames: connectionNamesFor(qe, codes, ordered),
|
|
668
|
+
connectionNames: connectionNamesFor(qe, codes, ordered, diagonal),
|
|
626
669
|
nUnits,
|
|
627
670
|
nConnections,
|
|
628
671
|
dims,
|
|
@@ -641,7 +684,8 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
641
684
|
eigenvalues: rs.eigenvalues,
|
|
642
685
|
centerVec,
|
|
643
686
|
codes,
|
|
644
|
-
adjacencyKey: buildAdjacencyKey(codes, ordered),
|
|
687
|
+
adjacencyKey: buildAdjacencyKey(codes, ordered, diagonal),
|
|
688
|
+
selfWeight,
|
|
645
689
|
});
|
|
646
690
|
}
|
|
647
691
|
|
|
@@ -657,6 +701,12 @@ const LIBENA_FUNCTIONS = new Set([
|
|
|
657
701
|
'directed_node_positions',
|
|
658
702
|
'directed_node_positions_combine_pairs',
|
|
659
703
|
'move_nodes_to_unit_circle',
|
|
704
|
+
'undirected_connection_key',
|
|
705
|
+
'directed_connection_key',
|
|
706
|
+
'node_weights_by_key',
|
|
707
|
+
'node_positions_by_key',
|
|
708
|
+
'node_centroids_by_key',
|
|
709
|
+
'move_nodes_to_unit_circle_by_key',
|
|
660
710
|
'ena_svd',
|
|
661
711
|
'deflate',
|
|
662
712
|
'orthogonal_svd',
|
|
@@ -675,6 +725,11 @@ const LIBENA_FUNCTIONS = new Set([
|
|
|
675
725
|
'accumulate_tensor_unit',
|
|
676
726
|
'aggregate_row_connections',
|
|
677
727
|
'finalize_row_connections',
|
|
728
|
+
'accumulate_tensor_unit_misses',
|
|
729
|
+
'finalize_self_connections',
|
|
730
|
+
'aggregate_self_connections',
|
|
731
|
+
'accumulate_unit_networks',
|
|
732
|
+
'weight_rows',
|
|
678
733
|
]);
|
|
679
734
|
|
|
680
735
|
/**
|
|
@@ -741,6 +796,14 @@ export default async function loadENA() {
|
|
|
741
796
|
* origin and out of the centring mean (= R's
|
|
742
797
|
* center.align.to.origin); false centres on
|
|
743
798
|
* every unit. Unordered only.
|
|
799
|
+
* @param {boolean} [opts.misses=true] - Also accumulate missed co-occurrences
|
|
800
|
+
* (missCounts, selfMissCounts).
|
|
801
|
+
* @param {number} [opts.selfWeight=2] - Ordered only: weight of a self-connection
|
|
802
|
+
* (ground i -> response i) in its code's node
|
|
803
|
+
* weight: 2 = the node's row + column sum
|
|
804
|
+
* (Zhiqiang Cai's 2021 rule); 1 = once
|
|
805
|
+
* (= R's model(self_weight =)). Recorded as
|
|
806
|
+
* rotation.selfWeight.
|
|
744
807
|
*
|
|
745
808
|
* @returns {ENAModel}
|
|
746
809
|
*/
|
|
@@ -765,6 +828,9 @@ export default async function loadENA() {
|
|
|
765
828
|
rotationSet,
|
|
766
829
|
sphereNorm: useSphereNorm = true,
|
|
767
830
|
centerAlignToOrigin = true,
|
|
831
|
+
misses = true,
|
|
832
|
+
selfWeight = 2,
|
|
833
|
+
selfConnections = false,
|
|
768
834
|
} = opts;
|
|
769
835
|
|
|
770
836
|
if (!codes?.length) throw new Error('opts.codes is required');
|
|
@@ -785,19 +851,31 @@ export default async function loadENA() {
|
|
|
785
851
|
|
|
786
852
|
// Every model accumulates through the tensor path; a plain moving
|
|
787
853
|
// window is expressed as defaultTensor(window).
|
|
788
|
-
const
|
|
854
|
+
const diagonal = selfConnections === true && !ordered;
|
|
855
|
+
const { networks: rawNetworks, rowConnectionCounts,
|
|
856
|
+
selfNetworks, missNetworks, selfMissNetworks } = accumulateTensor(
|
|
789
857
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
790
858
|
unitOf, convoGroups, tensorDef ?? defaultTensor(windowSize),
|
|
791
|
-
ordered, binary, weight, horizons
|
|
859
|
+
ordered, binary, weight, horizons, misses, diagonal
|
|
792
860
|
);
|
|
793
|
-
const nConnections =
|
|
861
|
+
const nConnections = connectionCount(qe, nCodes, ordered, diagonal);
|
|
794
862
|
|
|
795
|
-
applyCodeMask(rawNetworks, codeMask, codes.length, nUnits, nConnections, ordered);
|
|
863
|
+
applyCodeMask(rawNetworks, codeMask, codes.length, nUnits, nConnections, ordered, diagonal);
|
|
864
|
+
applyCodeMask(missNetworks, codeMask, codes.length, nUnits, nConnections, ordered, diagonal);
|
|
865
|
+
applySelfMask(selfNetworks, codeMask, codes.length, nUnits);
|
|
866
|
+
applySelfMask(selfMissNetworks, codeMask, codes.length, nUnits);
|
|
796
867
|
|
|
797
|
-
|
|
868
|
+
const model = runPipeline(qe, rawNetworks, nUnits, nConnections, codes,
|
|
798
869
|
unitLabels, metaData, rotMethod, groupA, groupB,
|
|
799
870
|
dims, gParams, rowConnectionCounts, ordered,
|
|
800
|
-
rotationSet, { sphereNorm: useSphereNorm, centerAlignToOrigin
|
|
871
|
+
rotationSet, { sphereNorm: useSphereNorm, centerAlignToOrigin, selfWeight,
|
|
872
|
+
selfConnections: diagonal });
|
|
873
|
+
// Kept alongside the model, not used by it (= R's
|
|
874
|
+
// self.connection.counts, miss.counts, self.miss.counts).
|
|
875
|
+
model.selfConnectionCounts = selfNetworks; // nUnits × nCodes
|
|
876
|
+
model.missCounts = missNetworks; // nUnits × nConnections, or null
|
|
877
|
+
model.selfMissCounts = selfMissNetworks; // nUnits × nCodes, or null
|
|
878
|
+
return model;
|
|
801
879
|
},
|
|
802
880
|
|
|
803
881
|
/**
|
|
@@ -829,30 +907,39 @@ export default async function loadENA() {
|
|
|
829
907
|
weightModel,
|
|
830
908
|
unitsUsed,
|
|
831
909
|
horizons,
|
|
910
|
+
misses = true,
|
|
911
|
+
selfConnections = false,
|
|
832
912
|
} = opts;
|
|
833
913
|
|
|
834
914
|
const { codeMatrix, nRows, nCodes, nUnits, unitLabels,
|
|
835
915
|
unitOf, convoGroups, metaData } =
|
|
836
916
|
parseData(rows, codes, units, conversations, unitsUsed);
|
|
837
917
|
|
|
838
|
-
const
|
|
918
|
+
const diagonal = selfConnections === true && !ordered;
|
|
919
|
+
const { networks, rowConnectionCounts,
|
|
920
|
+
selfNetworks, missNetworks, selfMissNetworks } = accumulateTensor(
|
|
839
921
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
840
922
|
unitOf, convoGroups, tensorDef ?? defaultTensor(windowSize),
|
|
841
|
-
ordered, binary, weightModelName(weightModel), horizons
|
|
923
|
+
ordered, binary, weightModelName(weightModel), horizons, misses, diagonal
|
|
842
924
|
);
|
|
843
|
-
const nConnections =
|
|
925
|
+
const nConnections = connectionCount(qe, nCodes, ordered, diagonal);
|
|
844
926
|
|
|
845
|
-
applyCodeMask(networks, codeMask, codes.length, nUnits, nConnections, ordered);
|
|
927
|
+
applyCodeMask(networks, codeMask, codes.length, nUnits, nConnections, ordered, diagonal);
|
|
928
|
+
applyCodeMask(missNetworks, codeMask, codes.length, nUnits, nConnections, ordered, diagonal);
|
|
929
|
+
applySelfMask(selfNetworks, codeMask, codes.length, nUnits);
|
|
930
|
+
applySelfMask(selfMissNetworks, codeMask, codes.length, nUnits);
|
|
846
931
|
|
|
847
|
-
const connectionNames = connectionNamesFor(qe, codes, ordered);
|
|
932
|
+
const connectionNames = connectionNamesFor(qe, codes, ordered, diagonal);
|
|
848
933
|
return {
|
|
849
934
|
connectionCounts: networks, rowConnectionCounts, unitLabels, connectionNames,
|
|
935
|
+
selfConnectionCounts: selfNetworks, missCounts: missNetworks,
|
|
936
|
+
selfMissCounts: selfMissNetworks,
|
|
850
937
|
metaData, nUnits, nConnections,
|
|
851
938
|
// Retained so tuneWindowSize() can rebuild at other window sizes
|
|
852
939
|
// (= R's ENAAccumulation$`_function.call`).
|
|
853
940
|
_call: { rows, codes, units, conversations,
|
|
854
941
|
window: windowSize, binary, ordered, tensor: tensorDef,
|
|
855
|
-
weightModel, unitsUsed, horizons },
|
|
942
|
+
weightModel, unitsUsed, horizons, misses, selfConnections: diagonal },
|
|
856
943
|
};
|
|
857
944
|
},
|
|
858
945
|
|
|
@@ -906,7 +993,7 @@ export default async function loadENA() {
|
|
|
906
993
|
const { networks: raw } = accumulateTensor(
|
|
907
994
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
908
995
|
unitOf, convoGroups, defaultTensor(w), ordered, binary,
|
|
909
|
-
weightModelName(weightModel), horizons
|
|
996
|
+
weightModelName(weightModel), horizons, /*misses=*/false
|
|
910
997
|
);
|
|
911
998
|
const model = runPipeline(
|
|
912
999
|
qe, raw, nUnits, nConnections, codes,
|
|
@@ -1107,7 +1194,7 @@ export default async function loadENA() {
|
|
|
1107
1194
|
const { networks: raw } = accumulateTensor(
|
|
1108
1195
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
1109
1196
|
unitOf, convoGroups, tensorDef ?? defaultTensor(windowSize),
|
|
1110
|
-
ordered, binary, weightModelName(weightModel), horizons
|
|
1197
|
+
ordered, binary, weightModelName(weightModel), horizons, /*misses=*/false
|
|
1111
1198
|
);
|
|
1112
1199
|
const nConnections = ordered ? nCodes * nCodes : qe.choose_two(nCodes);
|
|
1113
1200
|
applyCodeMask(raw, codeMask, nCodes, nUnits, nConnections, ordered);
|
|
@@ -1262,11 +1349,23 @@ export default async function loadENA() {
|
|
|
1262
1349
|
moveNodesToUnitCircle(model, opts = {}) {
|
|
1263
1350
|
const { dims: plane = [0, 1], mode = 'equal' } = opts;
|
|
1264
1351
|
const { nCodes, ordered } = unitCircleArgs(model, plane, mode);
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
)
|
|
1352
|
+
// The fit's self-connection weight; models built before it was
|
|
1353
|
+
// recorded used 1 (libena counted self-connections once then).
|
|
1354
|
+
const selfWeight = model.rotation.selfWeight ?? 1;
|
|
1355
|
+
// Unordered: centroids from libena's key-driven weighting (as the
|
|
1356
|
+
// fit), self-connection columns included when the model has them.
|
|
1357
|
+
const diagonal = !ordered &&
|
|
1358
|
+
(model.rotation.adjacencyKey ?? []).some(([a, b]) => a === b);
|
|
1359
|
+
const key = ordered ? null : qe.undirected_connection_key(nCodes, diagonal);
|
|
1360
|
+
const r = ordered
|
|
1361
|
+
? qe.move_nodes_to_unit_circle(
|
|
1362
|
+
model.lineWeights, model.nUnits, model.nConnections,
|
|
1363
|
+
model.rotation.nodes, nCodes, model.dims,
|
|
1364
|
+
plane[0], plane[1], mode, ordered, selfWeight)
|
|
1365
|
+
: qe.move_nodes_to_unit_circle_by_key(
|
|
1366
|
+
model.lineWeights, model.nUnits, model.nConnections,
|
|
1367
|
+
model.rotation.nodes, nCodes, model.dims,
|
|
1368
|
+
plane[0], plane[1], mode, key.from, key.to, selfWeight);
|
|
1270
1369
|
const moved = Object.assign(Object.create(Object.getPrototypeOf(model)), model);
|
|
1271
1370
|
moved.rotation = { ...model.rotation, nodes: new Float64Array(r.nodes.data) };
|
|
1272
1371
|
moved.model = { ...model.model, centroids: new Float64Array(r.centroids.data) };
|