@qe-libs/rena-wasm 0.1.15 → 0.1.17
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 +103 -44
- package/src/pipeline.js +16 -4
- package/src/tensor.js +13 -5
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 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})},e:(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[]})},l:(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)),m:()=>Emval.toHandle({}),f:handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)},d:(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()}();
|
|
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 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 expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];return createNamedFunction(humanName,function(...args){destructors.length=0;var sp;if(useStackFrame)sp=stackSave();var thisWired;var rv;try{invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){var argType=argTypes[i+2];argsWired[i]=argType.toWireType(useStackFrame&&argType.argStackAlloc?null:destructors,args[i]);invokerFuncArgs.push(argsWired[i])}rv=cppInvokerFunc(...invokerFuncArgs)}finally{if(useStackFrame)stackRestore(sp)}return function(rv){if(needsDestructorStack)runDestructors(destructors);else for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null)argTypes[i].destructorFunction(param)}if(returns)return argTypes[0].fromWireType(rv)}(rv)})}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 argN=new Array(argCount);var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=8}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)}))},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.17",
|
|
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
|
@@ -120,7 +120,9 @@ function totalVariance(m, nRows, nCols) {
|
|
|
120
120
|
* Build the adjacency key — list of [codeA, codeB] pairs for each connection.
|
|
121
121
|
* Matches R's rotation$adjacency.key.
|
|
122
122
|
*
|
|
123
|
-
* 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).
|
|
124
126
|
* Ordered: all n² directed connections in column-major order — column
|
|
125
127
|
* j*n + i is [codes[i], codes[j]], ground codes[i] → response codes[j]
|
|
126
128
|
* (as R names it "codes[i] & codes[j]").
|
|
@@ -129,7 +131,7 @@ function totalVariance(m, nRows, nCols) {
|
|
|
129
131
|
* @param {boolean} [ordered=false]
|
|
130
132
|
* @returns {string[][]} length nConnections, each entry is [codeI, codeJ]
|
|
131
133
|
*/
|
|
132
|
-
function buildAdjacencyKey(codes, ordered = false) {
|
|
134
|
+
function buildAdjacencyKey(codes, ordered = false, diagonal = false) {
|
|
133
135
|
const key = [];
|
|
134
136
|
if (ordered) {
|
|
135
137
|
for (let j = 0; j < codes.length; j++)
|
|
@@ -137,12 +139,18 @@ function buildAdjacencyKey(codes, ordered = false) {
|
|
|
137
139
|
key.push([codes[i], codes[j]]);
|
|
138
140
|
return key;
|
|
139
141
|
}
|
|
140
|
-
for (let j =
|
|
141
|
-
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++)
|
|
142
144
|
key.push([codes[i], codes[j]]);
|
|
143
145
|
return key;
|
|
144
146
|
}
|
|
145
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
|
+
|
|
146
154
|
/**
|
|
147
155
|
* Connection names, "codeA & codeB" per connection, in network column order
|
|
148
156
|
* (= R's colnames(set$connection.counts)).
|
|
@@ -152,9 +160,9 @@ function buildAdjacencyKey(codes, ordered = false) {
|
|
|
152
160
|
* @param {boolean} [ordered=false]
|
|
153
161
|
* @returns {string[]}
|
|
154
162
|
*/
|
|
155
|
-
function connectionNamesFor(qe, codes, ordered = false) {
|
|
156
|
-
if (!ordered) return qe.connection_names(codes);
|
|
157
|
-
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}`);
|
|
158
166
|
}
|
|
159
167
|
|
|
160
168
|
// ── ENA result object ─────────────────────────────────────────────────────────
|
|
@@ -191,6 +199,9 @@ class ENAModel {
|
|
|
191
199
|
centerVec: opts.centerVec,
|
|
192
200
|
codes: opts.codes,
|
|
193
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,
|
|
194
205
|
};
|
|
195
206
|
|
|
196
207
|
// ── column class annotations (mirrors R's S3 class tags) ─────────────
|
|
@@ -278,8 +289,9 @@ function weightModelName(name) {
|
|
|
278
289
|
* @param {number} nUnits
|
|
279
290
|
* @param {number} nConnections
|
|
280
291
|
* @param {boolean} ordered
|
|
292
|
+
* @param {boolean} [diagonal=false] unordered with self-connection columns
|
|
281
293
|
*/
|
|
282
|
-
function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered) {
|
|
294
|
+
function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered, diagonal = false) {
|
|
283
295
|
if (!codeMask || codeMask.length !== nCodes) return;
|
|
284
296
|
const zeroColumn = (k) => {
|
|
285
297
|
for (let u = 0; u < nUnits; u++) networks[u * nConnections + k] = 0;
|
|
@@ -291,8 +303,8 @@ function applyCodeMask(networks, codeMask, nCodes, nUnits, nConnections, ordered
|
|
|
291
303
|
return;
|
|
292
304
|
}
|
|
293
305
|
let k = 0;
|
|
294
|
-
for (let col = 1; col < nCodes; col++) {
|
|
295
|
-
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++) {
|
|
296
308
|
if ((codeMask[row] && codeMask[row][col] === 0) ||
|
|
297
309
|
(codeMask[col] && codeMask[col][row] === 0)) zeroColumn(k);
|
|
298
310
|
k++;
|
|
@@ -372,7 +384,8 @@ function unitCircleArgs(model, plane, mode) {
|
|
|
372
384
|
if (plane[0] === plane[1]) throw new Error(`${name}: the two dimensions must differ`);
|
|
373
385
|
const nCodes = codes.length;
|
|
374
386
|
const ordered = nConnections === nCodes * nCodes;
|
|
375
|
-
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
|
|
376
389
|
throw new Error(`${name}: ${nConnections} connections do not fit ${nCodes} codes`);
|
|
377
390
|
}
|
|
378
391
|
checkPoints(name + ' (nodes)', nodes, nCodes, dims);
|
|
@@ -397,7 +410,7 @@ function unitCircleArgs(model, plane, mode) {
|
|
|
397
410
|
* nodes: number[][], centerVec: Float64Array,
|
|
398
411
|
* eigenvalues: number[]|null, columnNames: string[] }}
|
|
399
412
|
*/
|
|
400
|
-
function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
413
|
+
function resolveRotationSet(rs, codes, nConnections, ordered, diagonal = false) {
|
|
401
414
|
const rot = matrixRows(rs.rotationMatrix, rs.rotationCols);
|
|
402
415
|
if (!rot || rot.length !== nConnections) {
|
|
403
416
|
throw new Error(
|
|
@@ -425,8 +438,8 @@ function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
|
425
438
|
if (src.length !== codes.length || codeIdx.some(i => i < 0)) {
|
|
426
439
|
throw new Error('rotationSet.codes do not match this model\'s codes');
|
|
427
440
|
}
|
|
428
|
-
const srcKey = new Map(buildAdjacencyKey(src, ordered).map(([a, b], k) => [a + '\u0000' + b, k]));
|
|
429
|
-
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]) => {
|
|
430
443
|
const k = srcKey.get(a + '\u0000' + b) ?? (ordered ? undefined : srcKey.get(b + '\u0000' + a));
|
|
431
444
|
if (k === undefined) throw new Error(`rotationSet has no connection '${a} & ${b}'`);
|
|
432
445
|
return k;
|
|
@@ -448,17 +461,25 @@ function resolveRotationSet(rs, codes, nConnections, ordered) {
|
|
|
448
461
|
|
|
449
462
|
// ── shared pipeline (post-accumulation) ──────────────────────────────────────
|
|
450
463
|
|
|
451
|
-
// norm: { sphereNorm = true, centerAlignToOrigin = true
|
|
452
|
-
// model(normalize =)
|
|
453
|
-
// applies to every model; centerAlignToOrigin
|
|
454
|
-
// 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, ...).
|
|
455
471
|
function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
456
472
|
metaData, rotMethod, groupA, groupB, dims, gParams,
|
|
457
473
|
rowConnectionCounts = null, ordered = false, rotationSet = null,
|
|
458
474
|
norm = {}) {
|
|
459
|
-
|
|
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);
|
|
460
480
|
const useSphereNorm = norm.sphereNorm !== false;
|
|
461
481
|
const alignToOrigin = ordered || norm.centerAlignToOrigin !== false;
|
|
482
|
+
const selfWeight = norm.selfWeight ?? 2;
|
|
462
483
|
|
|
463
484
|
// Sphere norm → lineWeights (= R's set$line.weights). Without it, every
|
|
464
485
|
// network is scaled by the largest network's length (fun_skip_sphere_norm).
|
|
@@ -483,8 +504,8 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
483
504
|
return runCustomRotation(qe, rawNetworks, lineWeights, pointsForProjection,
|
|
484
505
|
centerVec, nUnits, nConnections, codes, unitLabels,
|
|
485
506
|
metaData, dims, rowConnectionCounts, ordered,
|
|
486
|
-
resolveRotationSet(rotationSet, codes, nConnections, ordered),
|
|
487
|
-
alignToOrigin);
|
|
507
|
+
resolveRotationSet(rotationSet, codes, nConnections, ordered, diagonal),
|
|
508
|
+
alignToOrigin, selfWeight, diagonal);
|
|
488
509
|
}
|
|
489
510
|
|
|
490
511
|
// Rotate
|
|
@@ -527,7 +548,8 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
527
548
|
// Ordered (ONA) models use libqe's directed_node_positions, as
|
|
528
549
|
// ona::model() does (via rENA's optimize()).
|
|
529
550
|
const { nodes, centroids } = nodePositions(
|
|
530
|
-
qe, lineWeights, nUnits, nConnections, points, dims, ordered
|
|
551
|
+
qe, lineWeights, nUnits, nConnections, points, dims, ordered, selfWeight,
|
|
552
|
+
key, codes.length
|
|
531
553
|
);
|
|
532
554
|
|
|
533
555
|
// ONA: translate points and nodes so the points' mean is at the origin
|
|
@@ -558,7 +580,7 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
558
580
|
const variance = computeVariance(points, nUnits, dims, total);
|
|
559
581
|
|
|
560
582
|
// Adjacency key (= R's rotation$adjacency.key)
|
|
561
|
-
const adjacencyKey = buildAdjacencyKey(codes, ordered);
|
|
583
|
+
const adjacencyKey = buildAdjacencyKey(codes, ordered, diagonal);
|
|
562
584
|
|
|
563
585
|
return new ENAModel({
|
|
564
586
|
// top-level
|
|
@@ -584,12 +606,14 @@ function runPipeline(qe, rawNetworks, nUnits, nConnections, codes, unitLabels,
|
|
|
584
606
|
centerVec,
|
|
585
607
|
codes,
|
|
586
608
|
adjacencyKey,
|
|
609
|
+
selfWeight,
|
|
587
610
|
});
|
|
588
611
|
}
|
|
589
612
|
|
|
590
613
|
function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterVec,
|
|
591
614
|
nUnits, nConnections, codes, unitLabels, metaData, dims,
|
|
592
|
-
rowConnectionCounts, ordered, rs, alignToOrigin = true
|
|
615
|
+
rowConnectionCounts, ordered, rs, alignToOrigin = true,
|
|
616
|
+
selfWeight = 2, diagonal = false) {
|
|
593
617
|
let pointsForProjection = ownCentered;
|
|
594
618
|
let centerVec = ownCenterVec;
|
|
595
619
|
if (!ordered) {
|
|
@@ -626,9 +650,11 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
626
650
|
rs.nodes.forEach((row, c) => { for (let d = 0; d < dims; d++) nodes[c * dims + d] = Number(row[d]) || 0; });
|
|
627
651
|
let centroids;
|
|
628
652
|
if (ordered) {
|
|
629
|
-
centroids = nodePositions(qe, lineWeights, nUnits, nConnections, points, dims, true).centroids;
|
|
653
|
+
centroids = nodePositions(qe, lineWeights, nUnits, nConnections, points, dims, true, selfWeight).centroids;
|
|
630
654
|
} else {
|
|
631
|
-
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);
|
|
632
658
|
centroids = matmul(Float64Array.from(w.data), nUnits, w.cols, nodes, dims);
|
|
633
659
|
}
|
|
634
660
|
|
|
@@ -639,7 +665,7 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
639
665
|
points,
|
|
640
666
|
rotationMatrix,
|
|
641
667
|
metaData,
|
|
642
|
-
connectionNames: connectionNamesFor(qe, codes, ordered),
|
|
668
|
+
connectionNames: connectionNamesFor(qe, codes, ordered, diagonal),
|
|
643
669
|
nUnits,
|
|
644
670
|
nConnections,
|
|
645
671
|
dims,
|
|
@@ -658,7 +684,8 @@ function runCustomRotation(qe, rawNetworks, lineWeights, ownCentered, ownCenterV
|
|
|
658
684
|
eigenvalues: rs.eigenvalues,
|
|
659
685
|
centerVec,
|
|
660
686
|
codes,
|
|
661
|
-
adjacencyKey: buildAdjacencyKey(codes, ordered),
|
|
687
|
+
adjacencyKey: buildAdjacencyKey(codes, ordered, diagonal),
|
|
688
|
+
selfWeight,
|
|
662
689
|
});
|
|
663
690
|
}
|
|
664
691
|
|
|
@@ -674,6 +701,12 @@ const LIBENA_FUNCTIONS = new Set([
|
|
|
674
701
|
'directed_node_positions',
|
|
675
702
|
'directed_node_positions_combine_pairs',
|
|
676
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',
|
|
677
710
|
'ena_svd',
|
|
678
711
|
'deflate',
|
|
679
712
|
'orthogonal_svd',
|
|
@@ -763,6 +796,14 @@ export default async function loadENA() {
|
|
|
763
796
|
* origin and out of the centring mean (= R's
|
|
764
797
|
* center.align.to.origin); false centres on
|
|
765
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.
|
|
766
807
|
*
|
|
767
808
|
* @returns {ENAModel}
|
|
768
809
|
*/
|
|
@@ -788,6 +829,8 @@ export default async function loadENA() {
|
|
|
788
829
|
sphereNorm: useSphereNorm = true,
|
|
789
830
|
centerAlignToOrigin = true,
|
|
790
831
|
misses = true,
|
|
832
|
+
selfWeight = 2,
|
|
833
|
+
selfConnections = false,
|
|
791
834
|
} = opts;
|
|
792
835
|
|
|
793
836
|
if (!codes?.length) throw new Error('opts.codes is required');
|
|
@@ -808,23 +851,25 @@ export default async function loadENA() {
|
|
|
808
851
|
|
|
809
852
|
// Every model accumulates through the tensor path; a plain moving
|
|
810
853
|
// window is expressed as defaultTensor(window).
|
|
854
|
+
const diagonal = selfConnections === true && !ordered;
|
|
811
855
|
const { networks: rawNetworks, rowConnectionCounts,
|
|
812
856
|
selfNetworks, missNetworks, selfMissNetworks } = accumulateTensor(
|
|
813
857
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
814
858
|
unitOf, convoGroups, tensorDef ?? defaultTensor(windowSize),
|
|
815
|
-
ordered, binary, weight, horizons, misses
|
|
859
|
+
ordered, binary, weight, horizons, misses, diagonal
|
|
816
860
|
);
|
|
817
|
-
const nConnections =
|
|
861
|
+
const nConnections = connectionCount(qe, nCodes, ordered, diagonal);
|
|
818
862
|
|
|
819
|
-
applyCodeMask(rawNetworks, codeMask, codes.length, nUnits, nConnections, ordered);
|
|
820
|
-
applyCodeMask(missNetworks, 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);
|
|
821
865
|
applySelfMask(selfNetworks, codeMask, codes.length, nUnits);
|
|
822
866
|
applySelfMask(selfMissNetworks, codeMask, codes.length, nUnits);
|
|
823
867
|
|
|
824
868
|
const model = runPipeline(qe, rawNetworks, nUnits, nConnections, codes,
|
|
825
869
|
unitLabels, metaData, rotMethod, groupA, groupB,
|
|
826
870
|
dims, gParams, rowConnectionCounts, ordered,
|
|
827
|
-
rotationSet, { sphereNorm: useSphereNorm, centerAlignToOrigin
|
|
871
|
+
rotationSet, { sphereNorm: useSphereNorm, centerAlignToOrigin, selfWeight,
|
|
872
|
+
selfConnections: diagonal });
|
|
828
873
|
// Kept alongside the model, not used by it (= R's
|
|
829
874
|
// self.connection.counts, miss.counts, self.miss.counts).
|
|
830
875
|
model.selfConnectionCounts = selfNetworks; // nUnits × nCodes
|
|
@@ -863,26 +908,28 @@ export default async function loadENA() {
|
|
|
863
908
|
unitsUsed,
|
|
864
909
|
horizons,
|
|
865
910
|
misses = true,
|
|
911
|
+
selfConnections = false,
|
|
866
912
|
} = opts;
|
|
867
913
|
|
|
868
914
|
const { codeMatrix, nRows, nCodes, nUnits, unitLabels,
|
|
869
915
|
unitOf, convoGroups, metaData } =
|
|
870
916
|
parseData(rows, codes, units, conversations, unitsUsed);
|
|
871
917
|
|
|
918
|
+
const diagonal = selfConnections === true && !ordered;
|
|
872
919
|
const { networks, rowConnectionCounts,
|
|
873
920
|
selfNetworks, missNetworks, selfMissNetworks } = accumulateTensor(
|
|
874
921
|
qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
875
922
|
unitOf, convoGroups, tensorDef ?? defaultTensor(windowSize),
|
|
876
|
-
ordered, binary, weightModelName(weightModel), horizons, misses
|
|
923
|
+
ordered, binary, weightModelName(weightModel), horizons, misses, diagonal
|
|
877
924
|
);
|
|
878
|
-
const nConnections =
|
|
925
|
+
const nConnections = connectionCount(qe, nCodes, ordered, diagonal);
|
|
879
926
|
|
|
880
|
-
applyCodeMask(networks, codeMask, codes.length, nUnits, nConnections, ordered);
|
|
881
|
-
applyCodeMask(missNetworks, 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);
|
|
882
929
|
applySelfMask(selfNetworks, codeMask, codes.length, nUnits);
|
|
883
930
|
applySelfMask(selfMissNetworks, codeMask, codes.length, nUnits);
|
|
884
931
|
|
|
885
|
-
const connectionNames = connectionNamesFor(qe, codes, ordered);
|
|
932
|
+
const connectionNames = connectionNamesFor(qe, codes, ordered, diagonal);
|
|
886
933
|
return {
|
|
887
934
|
connectionCounts: networks, rowConnectionCounts, unitLabels, connectionNames,
|
|
888
935
|
selfConnectionCounts: selfNetworks, missCounts: missNetworks,
|
|
@@ -892,7 +939,7 @@ export default async function loadENA() {
|
|
|
892
939
|
// (= R's ENAAccumulation$`_function.call`).
|
|
893
940
|
_call: { rows, codes, units, conversations,
|
|
894
941
|
window: windowSize, binary, ordered, tensor: tensorDef,
|
|
895
|
-
weightModel, unitsUsed, horizons, misses },
|
|
942
|
+
weightModel, unitsUsed, horizons, misses, selfConnections: diagonal },
|
|
896
943
|
};
|
|
897
944
|
},
|
|
898
945
|
|
|
@@ -1302,11 +1349,23 @@ export default async function loadENA() {
|
|
|
1302
1349
|
moveNodesToUnitCircle(model, opts = {}) {
|
|
1303
1350
|
const { dims: plane = [0, 1], mode = 'equal' } = opts;
|
|
1304
1351
|
const { nCodes, ordered } = unitCircleArgs(model, plane, mode);
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
)
|
|
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);
|
|
1310
1369
|
const moved = Object.assign(Object.create(Object.getPrototypeOf(model)), model);
|
|
1311
1370
|
moved.rotation = { ...model.rotation, nodes: new Float64Array(r.nodes.data) };
|
|
1312
1371
|
moved.model = { ...model.model, centroids: new Float64Array(r.centroids.data) };
|
package/src/pipeline.js
CHANGED
|
@@ -319,17 +319,29 @@ export function project(centered, nUnits, nConnections, rotation, rotRows, rotCo
|
|
|
319
319
|
/**
|
|
320
320
|
* Compute code node positions via least-squares (LWS).
|
|
321
321
|
*
|
|
322
|
-
* @param {boolean} [directed=false] Use
|
|
322
|
+
* @param {boolean} [directed=false] Use libena's directed_node_positions (for
|
|
323
323
|
* ordered n² networks), as rENA's optimize() does for ordered sets.
|
|
324
|
+
* @param {number} [selfWeight=2] Weight of a self-connection in its code's
|
|
325
|
+
* node weight (2 = row + column sum, the default; 1 = once).
|
|
326
|
+
* @param {{from, to}|null} [key=null] Unordered: libena's column key
|
|
327
|
+
* (undirected_connection_key); the nodes come from node_positions_by_key --
|
|
328
|
+
* the same as node_positions for choose(n, 2) columns, and it also places
|
|
329
|
+
* self-connection columns. null keeps node_positions.
|
|
330
|
+
* @param {number|null} [nCodes=null] Number of codes (with `key`).
|
|
324
331
|
* @returns {{ nodes: Float64Array, nodeRows: number, nodeCols: number,
|
|
325
332
|
* centroids: Float64Array|null }}
|
|
326
333
|
* nodes — code positions in ENA space (= R's rotation$nodes)
|
|
327
334
|
* centroids — LWS unit centroid positions (= R's model$centroids), or null
|
|
328
335
|
* if libqe does not expose them
|
|
329
336
|
*/
|
|
330
|
-
export function nodePositions(qe, networks, nUnits, nConnections, points, nDims,
|
|
331
|
-
|
|
332
|
-
const r =
|
|
337
|
+
export function nodePositions(qe, networks, nUnits, nConnections, points, nDims,
|
|
338
|
+
directed = false, selfWeight = 2, key = null, nCodes = null) {
|
|
339
|
+
const r = directed
|
|
340
|
+
? qe.directed_node_positions(networks, nUnits, nConnections, points, nUnits, nDims, nDims, selfWeight)
|
|
341
|
+
: key
|
|
342
|
+
? qe.node_positions_by_key(networks, nUnits, nConnections, points, nUnits, nDims, nDims,
|
|
343
|
+
key.from, key.to, nCodes, selfWeight)
|
|
344
|
+
: qe.node_positions(networks, nUnits, nConnections, points, nUnits, nDims, nDims);
|
|
333
345
|
return {
|
|
334
346
|
nodes: new Float64Array(r.nodes.data),
|
|
335
347
|
nodeRows: r.nodes.rows,
|
package/src/tensor.js
CHANGED
|
@@ -376,6 +376,9 @@ export function buildHorizonContexts(rows, unitOf, nUnits, horizons) {
|
|
|
376
376
|
* convoGroups as the windowing contexts
|
|
377
377
|
* @param {boolean} [misses=true] also accumulate missed co-occurrences
|
|
378
378
|
* (ground i present, response j absent)
|
|
379
|
+
* @param {boolean} [diagonal=false] unordered only: self-connections are
|
|
380
|
+
* also connection columns (A & A, A & B,
|
|
381
|
+
* B & B, ...; n(n+1)/2 columns)
|
|
379
382
|
*
|
|
380
383
|
* @returns {{ networks: Float64Array, rowConnectionCounts: Float64Array,
|
|
381
384
|
* selfNetworks: Float64Array, missNetworks: Float64Array|null,
|
|
@@ -392,7 +395,7 @@ export function buildHorizonContexts(rows, unitOf, nUnits, horizons) {
|
|
|
392
395
|
export function accumulateTensor(qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
393
396
|
unitOf, convoGroups, tensorDef, ordered = false,
|
|
394
397
|
binary = true, weight = null, horizons = null,
|
|
395
|
-
misses = true) {
|
|
398
|
+
misses = true, diagonal = false) {
|
|
396
399
|
const {
|
|
397
400
|
dims,
|
|
398
401
|
dimsSender = [],
|
|
@@ -409,9 +412,10 @@ export function accumulateTensor(qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
|
409
412
|
validateTensor(dims, tensorData, factors, factorLevels);
|
|
410
413
|
const allTimes = timesCol ? parseTimes(rows, timesCol, timesEndCol || null) : null;
|
|
411
414
|
|
|
415
|
+
const withDiagonal = diagonal && !ordered;
|
|
412
416
|
const nConnections = ordered
|
|
413
417
|
? nCodes * nCodes
|
|
414
|
-
: qe.choose_two(nCodes);
|
|
418
|
+
: withDiagonal ? (nCodes * (nCodes + 1)) / 2 : qe.choose_two(nCodes);
|
|
415
419
|
|
|
416
420
|
const networks = new Float64Array(nUnits * nConnections);
|
|
417
421
|
const rowConnectionCounts = new Float64Array(nRows * nConnections);
|
|
@@ -451,15 +455,19 @@ export function accumulateTensor(qe, rows, codeMatrix, nRows, nCodes, nUnits,
|
|
|
451
455
|
// in R: fold (unordered), per-line weight model, unit sum and the
|
|
452
456
|
// self-connection diagonal, for hits and misses. Unit vectors are
|
|
453
457
|
// additive over lines, so a unit's contexts simply add up.
|
|
454
|
-
const
|
|
458
|
+
const args = [
|
|
455
459
|
tensorData, dimsArr,
|
|
456
460
|
senderArr, receiverArr, modeArr,
|
|
457
461
|
contextLookup, clRows, clCols,
|
|
458
462
|
new Int32Array(localRows),
|
|
459
463
|
ctxCodes, nCtx, nCodes,
|
|
460
464
|
times,
|
|
461
|
-
ordered, kernelWeight, misses
|
|
462
|
-
|
|
465
|
+
ordered, kernelWeight, misses,
|
|
466
|
+
];
|
|
467
|
+
// The trailing `diagonal` is an optional overload in libtma's binding.
|
|
468
|
+
const result = withDiagonal
|
|
469
|
+
? qe.accumulate_unit_networks(...args, true)
|
|
470
|
+
: qe.accumulate_unit_networks(...args);
|
|
463
471
|
const addUnit = (target, vec, width) => {
|
|
464
472
|
const off = unit * width;
|
|
465
473
|
for (let c = 0; c < width; c++) target[off + c] += vec[c];
|