vizmatic 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/PROMPT.md +32 -0
  2. package/README.md +8 -3
  3. package/ROADMAP.md +4 -2
  4. package/SCIENCE.md +69 -3
  5. package/dist/chunk-6JI55YX4.js +604 -0
  6. package/dist/{chunk-LTX44BAE.js → chunk-BYKXNUX7.js} +25 -4
  7. package/dist/{chunk-4MXGLMBG.js → chunk-EPZLNABN.js} +107 -37
  8. package/dist/chunk-EWCO6ZT6.js +696 -0
  9. package/dist/{chunk-JZPMGVBP.js → chunk-G7HRSKHV.js} +1 -1
  10. package/dist/{chunk-RPAHMKAR.js → chunk-JTWC2OPN.js} +7 -5
  11. package/dist/chunk-LJZO36IR.js +124 -0
  12. package/dist/chunk-REL2BZ2B.js +88 -0
  13. package/dist/chunk-RLPEOWST.js +1 -0
  14. package/dist/chunk-VMHOWCDL.js +296 -0
  15. package/dist/chunk-YDD63HHD.js +1 -0
  16. package/dist/{chunk-I745F4QK.js → chunk-YNGDEARY.js} +1134 -643
  17. package/dist/cli.js +80 -543
  18. package/dist/gpu-selection-CDWCZH27.js +1 -0
  19. package/dist/gpu-selection-MX6NHMNA.js +635 -0
  20. package/dist/index.cjs +473 -155
  21. package/dist/index.d.cts +30 -239
  22. package/dist/index.d.ts +30 -239
  23. package/dist/index.js +410 -457
  24. package/dist/math-E7W5LFWO.js +1 -0
  25. package/dist/{math-LXB4FH4E.js → math-NEFQUPRV.js} +3 -1
  26. package/dist/scene-browser.js +17 -17
  27. package/dist/scene-cli.js +1 -1
  28. package/dist/scene-runtime.cjs +4 -2
  29. package/dist/scene-runtime.js +2 -2
  30. package/dist/stage-browser/browser.d.ts +1206 -854
  31. package/dist/stage-browser/gpu-renderer.js +138 -0
  32. package/dist/stage-browser/{math-4WFNHVV2.js → math-KYHUOK7A.js} +46 -10
  33. package/dist/stage-browser/stage.js +107 -19
  34. package/dist/stage-export.cjs +8221 -6784
  35. package/dist/stage-export.d.cts +13 -5
  36. package/dist/stage-export.d.ts +13 -5
  37. package/dist/stage-export.js +111 -601
  38. package/dist/stage.cjs +6243 -3474
  39. package/dist/stage.d.cts +1064 -765
  40. package/dist/stage.d.ts +1064 -765
  41. package/dist/stage.js +3571 -2405
  42. package/dist/{svg-import-B5BGbC1t.d.cts → svg-import-CSCFWYaB.d.cts} +21 -12
  43. package/dist/{svg-import-B5BGbC1t.d.ts → svg-import-CSCFWYaB.d.ts} +21 -12
  44. package/dist/teaching-math-DTKc0XsB.d.cts +243 -0
  45. package/dist/teaching-math-ydDBhJ2M.d.ts +243 -0
  46. package/dist/{video-CiN1MDCS.d.cts → theme-DhVdDQKO.d.cts} +4 -237
  47. package/dist/{video-CiN1MDCS.d.ts → theme-DhVdDQKO.d.ts} +4 -237
  48. package/dist/video-BYCeOz8F.d.ts +259 -0
  49. package/dist/video-CGLxJXqu.d.cts +259 -0
  50. package/examples/catalog-science-physics.tsx +6 -6
  51. package/examples/films/_boltzmann-entropy/model.ts +63 -0
  52. package/examples/films/_catalysis/model.ts +49 -0
  53. package/examples/films/_gravitational-waves/model.ts +32 -0
  54. package/examples/films/_heat-equation/model.ts +54 -0
  55. package/examples/films/_hydrogen-orbitals/model.ts +31 -0
  56. package/examples/films/_maxwell/model.ts +84 -0
  57. package/examples/films/_planetary-orbits/appearance.ts +71 -0
  58. package/examples/films/_planetary-orbits/model.ts +152 -0
  59. package/examples/films/_planetary-orbits/saturn.ts +142 -0
  60. package/examples/films/_quantum-tunneling/model.ts +58 -0
  61. package/examples/films/_reaction-diffusion/model.ts +61 -0
  62. package/examples/films/_stationary-action/model.ts +38 -0
  63. package/examples/films/attention.ts +309 -253
  64. package/examples/films/beam-search.ts +321 -49
  65. package/examples/films/boltzmann-entropy.ts +104 -0
  66. package/examples/films/cache-miss.ts +387 -394
  67. package/examples/films/catalog.json +238 -77
  68. package/examples/films/catalysis.ts +128 -0
  69. package/examples/films/central-limit.ts +27 -22
  70. package/examples/films/complex-maps.ts +70 -56
  71. package/examples/films/deck-example.ts +261 -200
  72. package/examples/films/euler-circle.ts +72 -28
  73. package/examples/films/flash-attention.ts +549 -0
  74. package/examples/films/forecast.ts +2 -2
  75. package/examples/films/fourier-epicycles.ts +21 -20
  76. package/examples/films/gradient-descent.ts +23 -49
  77. package/examples/films/gravitational-waves.ts +179 -0
  78. package/examples/films/heat-equation.ts +124 -0
  79. package/examples/films/hydrogen-orbitals.ts +135 -0
  80. package/examples/films/io-uring.ts +635 -0
  81. package/examples/films/linear-maps.ts +42 -31
  82. package/examples/films/lorenz.ts +42 -79
  83. package/examples/films/maxwell.ts +197 -0
  84. package/examples/films/pathlines.ts +85 -0
  85. package/examples/films/planetary-orbits.ts +146 -0
  86. package/examples/films/pythagoras.ts +18 -10
  87. package/examples/films/quantum-tunneling.ts +116 -0
  88. package/examples/films/rag-citations.ts +423 -0
  89. package/examples/films/reaction-diffusion.ts +70 -0
  90. package/examples/films/ring-allreduce.ts +531 -0
  91. package/examples/films/stationary-action.ts +170 -0
  92. package/examples/films/svd-3d.ts +605 -0
  93. package/examples/films/taylor-series.ts +9 -9
  94. package/examples/films/vizmatic-title.ts +1 -0
  95. package/examples/vizmatic-hero.tsx +102 -32
  96. package/package.json +3 -1
  97. package/dist/chunk-3F2VQ7NW.js +0 -1
  98. package/dist/chunk-GGFDBJ25.js +0 -88
  99. package/dist/math-QVCETQDQ.js +0 -1
@@ -0,0 +1 @@
1
+ function convertIndexedToRgb(decodedImage){const palette=decodedImage.palette;const depth=decodedImage.depth;if(!palette){throw new Error("Color palette is undefined.")}checkDataSize(decodedImage);const indexSize=decodedImage.width*decodedImage.height;const resSize=indexSize*palette[0].length;const res=new Uint8Array(resSize);let indexPos=0;let offset=0;const indexes=new Uint8Array(indexSize);let bit=255;switch(depth){case 1:bit=128;break;case 2:bit=192;break;case 4:bit=240;break;case 8:bit=255;break;default:throw new Error("Incorrect depth value")}for(const byte of decodedImage.data){let bit2=bit;let shift=8;while(bit2){shift-=depth;indexes[indexPos++]=(byte&bit2)>>shift;bit2=bit2>>depth;if(indexPos%decodedImage.width===0){break}}}if(decodedImage.palette){for(const index of indexes){const color=decodedImage.palette.at(index);if(!color){throw new Error("Incorrect index of palette color")}res.set(color,offset);offset+=color.length}}return res}function checkDataSize(image){const expectedSize=image.depth<8?Math.ceil(image.width*image.depth/8)*image.height*image.channels:image.width*image.height*image.channels;if(image.data.length!==expectedSize){throw new RangeError(`wrong data size. Found ${image.data.length}, expected ${expectedSize}`)}}import{Unzlib as Inflator,unzlibSync}from"fflate";function decode(bytes,encoding="utf8"){const decoder=new TextDecoder(encoding);return decoder.decode(bytes)}var encoder=new TextEncoder;function encode(str){return encoder.encode(str)}var defaultByteLength=1024*8;var hostBigEndian=(()=>{const array=new Uint8Array(4);const view=new Uint32Array(array.buffer);return!((view[0]=1)&array[0])})();var typedArrays={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};var IOBuffer=class _IOBuffer{buffer;byteLength;byteOffset;length;offset;lastWrittenByte;littleEndian;_data;_mark;_marks;constructor(data=defaultByteLength,options={}){let dataIsGiven=false;if(typeof data==="number"){data=new ArrayBuffer(data)}else{dataIsGiven=true;this.lastWrittenByte=data.byteLength}const offset=options.offset?options.offset>>>0:0;const byteLength=data.byteLength-offset;let dvOffset=offset;if(ArrayBuffer.isView(data)||data instanceof _IOBuffer){if(data.byteLength!==data.buffer.byteLength){dvOffset=data.byteOffset+offset}data=data.buffer}if(dataIsGiven){this.lastWrittenByte=byteLength}else{this.lastWrittenByte=0}this.buffer=data;this.length=byteLength;this.byteLength=byteLength;this.byteOffset=dvOffset;this.offset=0;this.littleEndian=true;this._data=new DataView(this.buffer,dvOffset,byteLength);this._mark=0;this._marks=[]}available(byteLength=1){return this.offset+byteLength<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){this.littleEndian=true;return this}isBigEndian(){return!this.littleEndian}setBigEndian(){this.littleEndian=false;return this}skip(n=1){this.offset+=n;return this}back(n=1){this.offset-=n;return this}seek(offset){this.offset=offset;return this}mark(){this._mark=this.offset;return this}reset(){this.offset=this._mark;return this}pushMark(){this._marks.push(this.offset);return this}popMark(){const offset=this._marks.pop();if(offset===void 0){throw new Error("Mark stack empty")}this.seek(offset);return this}rewind(){this.offset=0;return this}ensureAvailable(byteLength=1){if(!this.available(byteLength)){const lengthNeeded=this.offset+byteLength;const newLength=lengthNeeded*2;const newArray=new Uint8Array(newLength);newArray.set(new Uint8Array(this.buffer));this.buffer=newArray.buffer;this.length=newLength;this.byteLength=newLength;this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(n=1){return this.readArray(n,"uint8")}readArray(size,type){const bytes=typedArrays[type].BYTES_PER_ELEMENT*size;const offset=this.byteOffset+this.offset;const slice=this.buffer.slice(offset,offset+bytes);if(this.littleEndian===hostBigEndian&&type!=="uint8"&&type!=="int8"){const slice2=new Uint8Array(this.buffer.slice(offset,offset+bytes));slice2.reverse();const returnArray2=new typedArrays[type](slice2.buffer);this.offset+=bytes;returnArray2.reverse();return returnArray2}const returnArray=new typedArrays[type](slice);this.offset+=bytes;return returnArray}readInt16(){const value=this._data.getInt16(this.offset,this.littleEndian);this.offset+=2;return value}readUint16(){const value=this._data.getUint16(this.offset,this.littleEndian);this.offset+=2;return value}readInt32(){const value=this._data.getInt32(this.offset,this.littleEndian);this.offset+=4;return value}readUint32(){const value=this._data.getUint32(this.offset,this.littleEndian);this.offset+=4;return value}readFloat32(){const value=this._data.getFloat32(this.offset,this.littleEndian);this.offset+=4;return value}readFloat64(){const value=this._data.getFloat64(this.offset,this.littleEndian);this.offset+=8;return value}readBigInt64(){const value=this._data.getBigInt64(this.offset,this.littleEndian);this.offset+=8;return value}readBigUint64(){const value=this._data.getBigUint64(this.offset,this.littleEndian);this.offset+=8;return value}readChar(){return String.fromCharCode(this.readInt8())}readChars(n=1){let result="";for(let i=0;i<n;i++){result+=this.readChar()}return result}readUtf8(n=1){return decode(this.readBytes(n))}decodeText(n=1,encoding="utf8"){return decode(this.readBytes(n),encoding)}writeBoolean(value){this.writeUint8(value?255:0);return this}writeInt8(value){this.ensureAvailable(1);this._data.setInt8(this.offset++,value);this._updateLastWrittenByte();return this}writeUint8(value){this.ensureAvailable(1);this._data.setUint8(this.offset++,value);this._updateLastWrittenByte();return this}writeByte(value){return this.writeUint8(value)}writeBytes(bytes){this.ensureAvailable(bytes.length);for(let i=0;i<bytes.length;i++){this._data.setUint8(this.offset++,bytes[i])}this._updateLastWrittenByte();return this}writeInt16(value){this.ensureAvailable(2);this._data.setInt16(this.offset,value,this.littleEndian);this.offset+=2;this._updateLastWrittenByte();return this}writeUint16(value){this.ensureAvailable(2);this._data.setUint16(this.offset,value,this.littleEndian);this.offset+=2;this._updateLastWrittenByte();return this}writeInt32(value){this.ensureAvailable(4);this._data.setInt32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeUint32(value){this.ensureAvailable(4);this._data.setUint32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeFloat32(value){this.ensureAvailable(4);this._data.setFloat32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeFloat64(value){this.ensureAvailable(8);this._data.setFloat64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeBigInt64(value){this.ensureAvailable(8);this._data.setBigInt64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeBigUint64(value){this.ensureAvailable(8);this._data.setBigUint64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeChar(str){return this.writeUint8(str.charCodeAt(0))}writeChars(str){for(let i=0;i<str.length;i++){this.writeUint8(str.charCodeAt(i))}return this}writeUtf8(str){return this.writeBytes(encode(str))}toArray(){return new Uint8Array(this.buffer,this.byteOffset,this.lastWrittenByte)}getWrittenByteLength(){return this.lastWrittenByte-this.byteOffset}_updateLastWrittenByte(){if(this.offset>this.lastWrittenByte){this.lastWrittenByte=this.offset}}};var crcTable=[];for(let n=0;n<256;n++){let c=n;for(let k=0;k<8;k++){if(c&1){c=3988292384^c>>>1}else{c=c>>>1}}crcTable[n]=c}var initialCrc=4294967295;function updateCrc(currentCrc,data,length){let c=currentCrc;for(let n=0;n<length;n++){c=crcTable[(c^data[n])&255]^c>>>8}return c}function crc(data,length){return(updateCrc(initialCrc,data,length)^initialCrc)>>>0}function checkCrc(buffer,crcLength,chunkName){const expectedCrc=buffer.readUint32();const actualCrc=crc(new Uint8Array(buffer.buffer,buffer.byteOffset+buffer.offset-crcLength-4,crcLength),crcLength);if(actualCrc!==expectedCrc){throw new Error(`CRC mismatch for chunk ${chunkName}. Expected ${expectedCrc}, found ${actualCrc}`)}}function writeCrc(buffer,length){buffer.writeUint32(crc(new Uint8Array(buffer.buffer,buffer.byteOffset+buffer.offset-length,length),length))}function unfilterNone(currentLine,newLine,bytesPerLine){for(let i=0;i<bytesPerLine;i++){newLine[i]=currentLine[i]}}function unfilterSub(currentLine,newLine,bytesPerLine,bytesPerPixel){let i=0;for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+newLine[i-bytesPerPixel]&255}}function unfilterUp(currentLine,newLine,prevLine,bytesPerLine){let i=0;if(prevLine.length===0){for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]}}else{for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+prevLine[i]&255}}}function unfilterAverage(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel){let i=0;if(prevLine.length===0){for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+(newLine[i-bytesPerPixel]>>1)&255}}else{for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]+(prevLine[i]>>1)&255}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+(newLine[i-bytesPerPixel]+prevLine[i]>>1)&255}}}function unfilterPaeth(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel){let i=0;if(prevLine.length===0){for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+newLine[i-bytesPerPixel]&255}}else{for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]+prevLine[i]&255}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+paethPredictor(newLine[i-bytesPerPixel],prevLine[i],prevLine[i-bytesPerPixel])&255}}}function paethPredictor(a,b,c){const p=a+b-c;const pa=Math.abs(p-a);const pb=Math.abs(p-b);const pc=Math.abs(p-c);if(pa<=pb&&pa<=pc)return a;else if(pb<=pc)return b;else return c}function applyUnfilter(filterType,currentLine,newLine,prevLine,passLineBytes,bytesPerPixel){switch(filterType){case 0:unfilterNone(currentLine,newLine,passLineBytes);break;case 1:unfilterSub(currentLine,newLine,passLineBytes,bytesPerPixel);break;case 2:unfilterUp(currentLine,newLine,prevLine,passLineBytes);break;case 3:unfilterAverage(currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);break;case 4:unfilterPaeth(currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);break;default:throw new Error(`Unsupported filter: ${filterType}`)}}var uint16=new Uint16Array([255]);var uint8=new Uint8Array(uint16.buffer);var osIsLittleEndian=uint8[0]===255;function decodeInterlaceAdam7(params){const{data,width,height,channels,depth}=params;const passes=[{x:0,y:0,xStep:8,yStep:8},{x:4,y:0,xStep:8,yStep:8},{x:0,y:4,xStep:4,yStep:8},{x:2,y:0,xStep:4,yStep:4},{x:0,y:2,xStep:2,yStep:4},{x:1,y:0,xStep:2,yStep:2},{x:0,y:1,xStep:1,yStep:2}];const bytesPerPixel=Math.ceil(depth/8)*channels;const resultData=new Uint8Array(height*width*bytesPerPixel);let offset=0;for(let passIndex=0;passIndex<7;passIndex++){const pass=passes[passIndex];const passWidth=Math.ceil((width-pass.x)/pass.xStep);const passHeight=Math.ceil((height-pass.y)/pass.yStep);if(passWidth<=0||passHeight<=0)continue;const passLineBytes=passWidth*bytesPerPixel;const prevLine=new Uint8Array(passLineBytes);for(let y=0;y<passHeight;y++){const filterType=data[offset++];const currentLine=data.subarray(offset,offset+passLineBytes);offset+=passLineBytes;const newLine=new Uint8Array(passLineBytes);applyUnfilter(filterType,currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);prevLine.set(newLine);for(let x=0;x<passWidth;x++){const outputX=pass.x+x*pass.xStep;const outputY=pass.y+y*pass.yStep;if(outputX>=width||outputY>=height)continue;for(let i=0;i<bytesPerPixel;i++){resultData[(outputY*width+outputX)*bytesPerPixel+i]=newLine[x*bytesPerPixel+i]}}}}if(depth===16){const uint16Data=new Uint16Array(resultData.buffer);if(osIsLittleEndian){for(let k=0;k<uint16Data.length;k++){uint16Data[k]=swap16(uint16Data[k])}}return uint16Data}else{return resultData}}function swap16(val){return(val&255)<<8|val>>8&255}var uint162=new Uint16Array([255]);var uint82=new Uint8Array(uint162.buffer);var osIsLittleEndian2=uint82[0]===255;var empty=new Uint8Array(0);function decodeInterlaceNull(params){const{data,width,height,channels,depth}=params;const bytesPerPixel=Math.ceil(depth/8)*channels;const bytesPerLine=Math.ceil(depth/8*channels*width);const newData=new Uint8Array(height*bytesPerLine);let prevLine=empty;let offset=0;let currentLine;let newLine;for(let i=0;i<height;i++){currentLine=data.subarray(offset+1,offset+1+bytesPerLine);newLine=newData.subarray(i*bytesPerLine,(i+1)*bytesPerLine);switch(data[offset]){case 0:unfilterNone(currentLine,newLine,bytesPerLine);break;case 1:unfilterSub(currentLine,newLine,bytesPerLine,bytesPerPixel);break;case 2:unfilterUp(currentLine,newLine,prevLine,bytesPerLine);break;case 3:unfilterAverage(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel);break;case 4:unfilterPaeth(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel);break;default:throw new Error(`Unsupported filter: ${data[offset]}`)}prevLine=newLine;offset+=bytesPerLine+1}if(depth===16){const uint16Data=new Uint16Array(newData.buffer);if(osIsLittleEndian2){for(let k=0;k<uint16Data.length;k++){uint16Data[k]=swap162(uint16Data[k])}}return uint16Data}else{return newData}}function swap162(val){return(val&255)<<8|val>>8&255}var pngSignature=Uint8Array.of(137,80,78,71,13,10,26,10);function writeSignature(buffer){buffer.writeBytes(pngSignature)}function checkSignature(buffer){if(!hasPngSignature(buffer.readBytes(pngSignature.length))){throw new Error("wrong PNG signature")}}function hasPngSignature(array){if(array.length<pngSignature.length){return false}for(let i=0;i<pngSignature.length;i++){if(array[i]!==pngSignature[i]){return false}}return true}var textChunkName="tEXt";var NULL=0;var latin1Decoder=new TextDecoder("latin1");function validateKeyword(keyword){validateLatin1(keyword);if(keyword.length===0||keyword.length>79){throw new Error("keyword length must be between 1 and 79")}}var latin1Regex=/^[\u0000-\u00FF]*$/;function validateLatin1(text){if(!latin1Regex.test(text)){throw new Error("invalid latin1 text")}}function decodetEXt(text,buffer,length){const keyword=readKeyword(buffer);text[keyword]=readLatin1(buffer,length-keyword.length-1)}function encodetEXt(buffer,keyword,text){validateKeyword(keyword);validateLatin1(text);const length=keyword.length+1+text.length;buffer.writeUint32(length);buffer.writeChars(textChunkName);buffer.writeChars(keyword);buffer.writeByte(NULL);buffer.writeChars(text);writeCrc(buffer,length+4)}function readKeyword(buffer){buffer.mark();while(buffer.readByte()!==NULL){}const end=buffer.offset;buffer.reset();const keyword=latin1Decoder.decode(buffer.readBytes(end-buffer.offset-1));buffer.skip(1);validateKeyword(keyword);return keyword}function readLatin1(buffer,length){return latin1Decoder.decode(buffer.readBytes(length))}var ColorType={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6};var CompressionMethod={UNKNOWN:-1,DEFLATE:0};var FilterMethod={UNKNOWN:-1,ADAPTIVE:0};var InterlaceMethod={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1};var DisposeOpType={NONE:0,BACKGROUND:1,PREVIOUS:2};var BlendOpType={SOURCE:0,OVER:1};var PngDecoder=class extends IOBuffer{_checkCrc;_inflator;_png;_apng;_end;_hasPalette;_palette;_hasTransparency;_transparency;_compressionMethod;_filterMethod;_interlaceMethod;_colorType;_isAnimated;_numberOfFrames;_numberOfPlays;_frames;_writingDataChunks;_chunks;_inflatorResult;constructor(data,options={}){super(data);const{checkCrc:checkCrc2=false}=options;this._checkCrc=checkCrc2;this._inflator=new Inflator((chunk,final)=>{this._chunks.push(chunk);if(final){const totalLength=this._chunks.reduce((sum,c)=>sum+c.length,0);this._inflatorResult=new Uint8Array(totalLength);let offset=0;for(const chunk2 of this._chunks){this._inflatorResult.set(chunk2,offset);offset+=chunk2.length}this._chunks=[]}});this._chunks=[];this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}};this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]};this._end=false;this._hasPalette=false;this._palette=[];this._hasTransparency=false;this._transparency=new Uint16Array(0);this._compressionMethod=CompressionMethod.UNKNOWN;this._filterMethod=FilterMethod.UNKNOWN;this._interlaceMethod=InterlaceMethod.UNKNOWN;this._colorType=ColorType.UNKNOWN;this._isAnimated=false;this._numberOfFrames=1;this._numberOfPlays=0;this._frames=[];this._writingDataChunks=false;this._inflatorResult=new Uint8Array(0);this.setBigEndian()}decode(){checkSignature(this);while(!this._end){const length=this.readUint32();const type=this.readChars(4);this.decodeChunk(length,type)}this._inflator.push(new Uint8Array(0),true);this.decodeImage();return this._png}decodeApng(){checkSignature(this);while(!this._end){const length=this.readUint32();const type=this.readChars(4);this.decodeApngChunk(length,type)}this.decodeApngImage();return this._apng}decodeChunk(length,type){const offset=this.offset;switch(type){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(length);break;case"IDAT":this.decodeIDAT(length);break;case"IEND":this._end=true;break;case"tRNS":this.decodetRNS(length);break;case"iCCP":this.decodeiCCP(length);break;case textChunkName:decodetEXt(this._png.text,this,length);break;case"pHYs":this.decodepHYs();break;default:this.skip(length);break}if(this.offset-offset!==length){throw new Error(`Length mismatch while decoding chunk ${type}`)}if(this._checkCrc){checkCrc(this,length+4,type)}else{this.skip(4)}}decodeApngChunk(length,type){const offset=this.offset;if(type!=="fdAT"&&type!=="IDAT"&&this._writingDataChunks){this.pushDataToFrame()}switch(type){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(length);break;default:this.decodeChunk(length,type);this.offset=offset+length;break}if(this.offset-offset!==length){throw new Error(`Length mismatch while decoding chunk ${type}`)}if(this._checkCrc){checkCrc(this,length+4,type)}else{this.skip(4)}}decodeIHDR(){const image=this._png;image.width=this.readUint32();image.height=this.readUint32();image.depth=checkBitDepth(this.readUint8());const colorType=this.readUint8();this._colorType=colorType;let channels;switch(colorType){case ColorType.GREYSCALE:channels=1;break;case ColorType.TRUECOLOUR:channels=3;break;case ColorType.INDEXED_COLOUR:channels=1;break;case ColorType.GREYSCALE_ALPHA:channels=2;break;case ColorType.TRUECOLOUR_ALPHA:channels=4;break;case ColorType.UNKNOWN:default:throw new Error(`Unknown color type: ${colorType}`)}this._png.channels=channels;this._compressionMethod=this.readUint8();if(this._compressionMethod!==CompressionMethod.DEFLATE){throw new Error(`Unsupported compression method: ${this._compressionMethod}`)}this._filterMethod=this.readUint8();this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32();this._numberOfPlays=this.readUint32();this._isAnimated=true}decodeFCTL(){const image={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(image)}decodePLTE(length){if(length%3!==0){throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`)}const l=length/3;this._hasPalette=true;const palette=[];this._palette=palette;for(let i=0;i<l;i++){palette.push([this.readUint8(),this.readUint8(),this.readUint8()])}}decodeIDAT(length){this._writingDataChunks=true;const dataLength=length;const dataOffset=this.offset+this.byteOffset;try{this._inflator.push(new Uint8Array(this.buffer,dataOffset,dataLength),false)}catch(error){throw new Error("Error while decompressing the data:",{cause:error})}this.skip(length)}decodeFDAT(length){this._writingDataChunks=true;let dataLength=length;let dataOffset=this.offset+this.byteOffset;dataOffset+=4;dataLength-=4;try{this._inflator.push(new Uint8Array(this.buffer,dataOffset,dataLength),false)}catch(error){throw new Error("Error while decompressing the data:",{cause:error})}this.skip(length)}decodetRNS(length){switch(this._colorType){case ColorType.GREYSCALE:case ColorType.TRUECOLOUR:{if(length%2!==0){throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${length}`)}if(length/2>this._png.width*this._png.height){throw new Error(`tRNS chunk contains more alpha values than there are pixels (${length/2} vs ${this._png.width*this._png.height})`)}this._hasTransparency=true;this._transparency=new Uint16Array(length/2);for(let i=0;i<length/2;i++){this._transparency[i]=this.readUint16()}break}case ColorType.INDEXED_COLOUR:{if(length>this._palette.length){throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`)}let i=0;for(;i<length;i++){const alpha=this.readByte();this._palette[i].push(alpha)}for(;i<this._palette.length;i++){this._palette[i].push(255)}break}case ColorType.UNKNOWN:case ColorType.GREYSCALE_ALPHA:case ColorType.TRUECOLOUR_ALPHA:default:{throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`)}}}decodeiCCP(length){const name=readKeyword(this);const compressionMethod=this.readUint8();if(compressionMethod!==CompressionMethod.DEFLATE){throw new Error(`Unsupported iCCP compression method: ${compressionMethod}`)}const compressedProfile=this.readBytes(length-name.length-2);this._png.iccEmbeddedProfile={name,profile:unzlibSync(compressedProfile)}}decodepHYs(){const ppuX=this.readUint32();const ppuY=this.readUint32();const unitSpecifier=this.readByte();this._png.resolution={x:ppuX,y:ppuY,unit:unitSpecifier}}decodeApngImage(){this._apng.width=this._png.width;this._apng.height=this._png.height;this._apng.channels=this._png.channels;this._apng.depth=this._png.depth;this._apng.numberOfFrames=this._numberOfFrames;this._apng.numberOfPlays=this._numberOfPlays;this._apng.text=this._png.text;this._apng.resolution=this._png.resolution;for(let i=0;i<this._numberOfFrames;i++){const newFrame={sequenceNumber:this._frames[i].sequenceNumber,delayNumber:this._frames[i].delayNumber,delayDenominator:this._frames[i].delayDenominator,data:this._apng.depth===8?new Uint8Array(this._apng.width*this._apng.height*this._apng.channels):new Uint16Array(this._apng.width*this._apng.height*this._apng.channels)};const frame=this._frames.at(i);if(frame){frame.data=decodeInterlaceNull({data:frame.data,width:frame.width,height:frame.height,channels:this._apng.channels,depth:this._apng.depth});if(this._hasPalette){this._apng.palette=this._palette}if(this._hasTransparency){this._apng.transparency=this._transparency}if(i===0||frame.xOffset===0&&frame.yOffset===0&&frame.width===this._png.width&&frame.height===this._png.height){newFrame.data=frame.data}else{const prevFrame=this._apng.frames.at(i-1);this.disposeFrame(frame,prevFrame,newFrame);this.addFrameDataToCanvas(newFrame,frame)}this._apng.frames.push(newFrame)}}return this._apng}disposeFrame(frame,prevFrame,imageFrame){switch(frame.disposeOp){case DisposeOpType.NONE:break;case DisposeOpType.BACKGROUND:for(let row=0;row<this._png.height;row++){for(let col=0;col<this._png.width;col++){const index=(row*frame.width+col)*this._png.channels;for(let channel=0;channel<this._png.channels;channel++){imageFrame.data[index+channel]=0}}}break;case DisposeOpType.PREVIOUS:imageFrame.data.set(prevFrame.data);break;default:throw new Error("Unknown disposeOp")}}addFrameDataToCanvas(imageFrame,frame){const maxValue=1<<this._png.depth;const calculatePixelIndices=(row,col)=>{const index=((row+frame.yOffset)*this._png.width+frame.xOffset+col)*this._png.channels;const frameIndex=(row*frame.width+col)*this._png.channels;return{index,frameIndex}};switch(frame.blendOp){case BlendOpType.SOURCE:for(let row=0;row<frame.height;row++){for(let col=0;col<frame.width;col++){const{index,frameIndex}=calculatePixelIndices(row,col);for(let channel=0;channel<this._png.channels;channel++){imageFrame.data[index+channel]=frame.data[frameIndex+channel]}}}break;case BlendOpType.OVER:for(let row=0;row<frame.height;row++){for(let col=0;col<frame.width;col++){const{index,frameIndex}=calculatePixelIndices(row,col);for(let channel=0;channel<this._png.channels;channel++){const sourceAlpha=frame.data[frameIndex+this._png.channels-1]/maxValue;const foregroundValue=channel%(this._png.channels-1)===0?1:frame.data[frameIndex+channel];const value=Math.floor(sourceAlpha*foregroundValue+(1-sourceAlpha)*imageFrame.data[index+channel]);imageFrame.data[index+channel]+=value}}}break;default:throw new Error("Unknown blendOp")}}decodeImage(){const data=this._inflatorResult;if(this._filterMethod!==FilterMethod.ADAPTIVE){throw new Error(`Filter method ${this._filterMethod} not supported`)}if(this._interlaceMethod===InterlaceMethod.NO_INTERLACE){this._png.data=decodeInterlaceNull({data,width:this._png.width,height:this._png.height,channels:this._png.channels,depth:this._png.depth})}else if(this._interlaceMethod===InterlaceMethod.ADAM7){this._png.data=decodeInterlaceAdam7({data,width:this._png.width,height:this._png.height,channels:this._png.channels,depth:this._png.depth})}else{throw new Error(`Interlace method ${this._interlaceMethod} not supported`)}if(this._hasPalette){this._png.palette=this._palette}if(this._hasTransparency){this._png.transparency=this._transparency}}pushDataToFrame(){this._inflator.push(new Uint8Array(0),true);const result=this._inflatorResult;const lastFrame=this._frames.at(-1);if(lastFrame){lastFrame.data=result}else{this._frames.push({sequenceNumber:0,width:this._png.width,height:this._png.height,xOffset:0,yOffset:0,delayNumber:0,delayDenominator:0,disposeOp:DisposeOpType.NONE,blendOp:BlendOpType.SOURCE,data:result})}this._inflator=new Inflator((chunk,final)=>{this._chunks.push(chunk);if(final){const totalLength=this._chunks.reduce((sum,c)=>sum+c.length,0);this._inflatorResult=new Uint8Array(totalLength);let offset=0;for(const chunk2 of this._chunks){this._inflatorResult.set(chunk2,offset);offset+=chunk2.length}this._chunks=[]}});this._chunks=[];this._writingDataChunks=false}};function checkBitDepth(value){if(value!==1&&value!==2&&value!==4&&value!==8&&value!==16){throw new Error(`invalid bit depth: ${value}`)}return value}import{zlibSync}from"fflate";var defaultZlibOptions={level:3};var PngEncoder=class extends IOBuffer{_png;_zlibOptions;_colorType;_interlaceMethod;constructor(data,options={}){super();this._colorType=ColorType.UNKNOWN;this._zlibOptions={...defaultZlibOptions,...options.zlib};this._png=this._checkData(data);this._interlaceMethod=(options.interlace==="Adam7"?InterlaceMethod.ADAM7:InterlaceMethod.NO_INTERLACE)??InterlaceMethod.NO_INTERLACE;this.setBigEndian()}encode(){writeSignature(this);this.encodeIHDR();if(this._png.palette){this.encodePLTE();if(this._png.palette[0].length===4){this.encodeTRNS()}}this.encodeData();if(this._png.text){for(const[keyword,text]of Object.entries(this._png.text)){encodetEXt(this,keyword,text)}}this.encodeIEND();return this.toArray()}encodeIHDR(){this.writeUint32(13);this.writeChars("IHDR");this.writeUint32(this._png.width);this.writeUint32(this._png.height);this.writeByte(this._png.depth);this.writeByte(this._colorType);this.writeByte(CompressionMethod.DEFLATE);this.writeByte(FilterMethod.ADAPTIVE);this.writeByte(this._interlaceMethod);writeCrc(this,17)}encodeIEND(){this.writeUint32(0);this.writeChars("IEND");writeCrc(this,4)}encodePLTE(){const paletteLength=this._png.palette?.length*3;this.writeUint32(paletteLength);this.writeChars("PLTE");for(const color of this._png.palette){this.writeByte(color[0]);this.writeByte(color[1]);this.writeByte(color[2])}writeCrc(this,4+paletteLength)}encodeTRNS(){const alpha=this._png.palette.filter(color=>{return color.at(-1)!==255});this.writeUint32(alpha.length);this.writeChars("tRNS");for(const el of alpha){this.writeByte(el.at(-1))}writeCrc(this,4+alpha.length)}encodeIDAT(data){this.writeUint32(data.length);this.writeChars("IDAT");this.writeBytes(data);writeCrc(this,data.length+4)}encodeData(){const{width,height,channels,depth,data}=this._png;const slotsPerLine=depth<=8?Math.ceil(width*depth/8)*channels:Math.ceil(width*depth/8*channels/2);const newData=new IOBuffer().setBigEndian();let offset=0;if(this._interlaceMethod===InterlaceMethod.NO_INTERLACE){for(let i=0;i<height;i++){newData.writeByte(0);if(depth===16){offset=writeDataUint16(data,newData,slotsPerLine,offset)}else{offset=writeDataBytes(data,newData,slotsPerLine,offset)}}}else if(this._interlaceMethod===InterlaceMethod.ADAM7){offset=writeDataInterlaced(this._png,data,newData,offset)}const buffer=newData.toArray();const compressed=zlibSync(buffer,this._zlibOptions);this.encodeIDAT(compressed)}_checkData(data){const{colorType,channels,depth}=getColorType(data,data.palette);const png={width:checkInteger(data.width,"width"),height:checkInteger(data.height,"height"),channels,data:data.data,depth,text:data.text,palette:data.palette};this._colorType=colorType;const expectedSize=depth<8?Math.ceil(png.width*depth/8)*png.height*channels:png.width*png.height*channels;if(png.data.length!==expectedSize){throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`)}return png}};function checkInteger(value,name){if(Number.isInteger(value)&&value>0){return value}throw new TypeError(`${name} must be a positive integer`)}function getColorType(data,palette){const{channels=4,depth=8}=data;if(channels!==4&&channels!==3&&channels!==2&&channels!==1){throw new RangeError(`unsupported number of channels: ${channels}`)}const returnValue={channels,depth,colorType:ColorType.UNKNOWN};switch(channels){case 4:returnValue.colorType=ColorType.TRUECOLOUR_ALPHA;break;case 3:returnValue.colorType=ColorType.TRUECOLOUR;break;case 1:if(palette){returnValue.colorType=ColorType.INDEXED_COLOUR}else{returnValue.colorType=ColorType.GREYSCALE}break;case 2:returnValue.colorType=ColorType.GREYSCALE_ALPHA;break;default:throw new Error("unsupported number of channels")}return returnValue}function writeDataBytes(data,newData,slotsPerLine,offset){for(let j=0;j<slotsPerLine;j++){newData.writeByte(data[offset++])}return offset}function writeDataInterlaced(imageData,data,newData,offset){const passes=[{x:0,y:0,xStep:8,yStep:8},{x:4,y:0,xStep:8,yStep:8},{x:0,y:4,xStep:4,yStep:8},{x:2,y:0,xStep:4,yStep:4},{x:0,y:2,xStep:2,yStep:4},{x:1,y:0,xStep:2,yStep:2},{x:0,y:1,xStep:1,yStep:2}];const{width,height,channels,depth}=imageData;let pixelSize;if(depth===16){pixelSize=channels*depth/8/2}else{pixelSize=channels*depth/8}for(let passIndex=0;passIndex<7;passIndex++){const pass=passes[passIndex];const passWidth=Math.floor((width-pass.x+pass.xStep-1)/pass.xStep);const passHeight=Math.floor((height-pass.y+pass.yStep-1)/pass.yStep);if(passWidth<=0||passHeight<=0)continue;const passLineBytes=passWidth*pixelSize;for(let y=0;y<passHeight;y++){const imageY=pass.y+y*pass.yStep;const rawScanline=depth<=8?new Uint8Array(passLineBytes):new Uint16Array(passLineBytes);let rawOffset=0;for(let x=0;x<passWidth;x++){const imageX=pass.x+x*pass.xStep;if(imageX<width&&imageY<height){const srcPos=(imageY*width+imageX)*pixelSize;for(let i=0;i<pixelSize;i++){rawScanline[rawOffset++]=data[srcPos+i]}}}newData.writeByte(0);if(depth===8){newData.writeBytes(rawScanline)}else if(depth===16){for(const value of rawScanline){newData.writeByte(value>>8&255);newData.writeByte(value&255)}}}}return offset}function writeDataUint16(data,newData,slotsPerLine,offset){for(let j=0;j<slotsPerLine;j++){newData.writeUint16(data[offset++])}return offset}function decodePng(data,options){const decoder=new PngDecoder(data,options);return decoder.decode()}function encodePng(png,options){const encoder2=new PngEncoder(png,options);return encoder2.encode()}export{convertIndexedToRgb,decodePng,encodePng};
@@ -0,0 +1,296 @@
1
+ // src/chemistry-elements.ts
2
+ var ELEMENT_SYMBOLS = Object.freeze([
3
+ "H",
4
+ "He",
5
+ "Li",
6
+ "Be",
7
+ "B",
8
+ "C",
9
+ "N",
10
+ "O",
11
+ "F",
12
+ "Ne",
13
+ "Na",
14
+ "Mg",
15
+ "Al",
16
+ "Si",
17
+ "P",
18
+ "S",
19
+ "Cl",
20
+ "Ar",
21
+ "K",
22
+ "Ca",
23
+ "Sc",
24
+ "Ti",
25
+ "V",
26
+ "Cr",
27
+ "Mn",
28
+ "Fe",
29
+ "Co",
30
+ "Ni",
31
+ "Cu",
32
+ "Zn",
33
+ "Ga",
34
+ "Ge",
35
+ "As",
36
+ "Se",
37
+ "Br",
38
+ "Kr",
39
+ "Rb",
40
+ "Sr",
41
+ "Y",
42
+ "Zr",
43
+ "Nb",
44
+ "Mo",
45
+ "Tc",
46
+ "Ru",
47
+ "Rh",
48
+ "Pd",
49
+ "Ag",
50
+ "Cd",
51
+ "In",
52
+ "Sn",
53
+ "Sb",
54
+ "Te",
55
+ "I",
56
+ "Xe",
57
+ "Cs",
58
+ "Ba",
59
+ "La",
60
+ "Ce",
61
+ "Pr",
62
+ "Nd",
63
+ "Pm",
64
+ "Sm",
65
+ "Eu",
66
+ "Gd",
67
+ "Tb",
68
+ "Dy",
69
+ "Ho",
70
+ "Er",
71
+ "Tm",
72
+ "Yb",
73
+ "Lu",
74
+ "Hf",
75
+ "Ta",
76
+ "W",
77
+ "Re",
78
+ "Os",
79
+ "Ir",
80
+ "Pt",
81
+ "Au",
82
+ "Hg",
83
+ "Tl",
84
+ "Pb",
85
+ "Bi",
86
+ "Po",
87
+ "At",
88
+ "Rn",
89
+ "Fr",
90
+ "Ra",
91
+ "Ac",
92
+ "Th",
93
+ "Pa",
94
+ "U",
95
+ "Np",
96
+ "Pu",
97
+ "Am",
98
+ "Cm",
99
+ "Bk",
100
+ "Cf",
101
+ "Es",
102
+ "Fm",
103
+ "Md",
104
+ "No",
105
+ "Lr",
106
+ "Rf",
107
+ "Db",
108
+ "Sg",
109
+ "Bh",
110
+ "Hs",
111
+ "Mt",
112
+ "Ds",
113
+ "Rg",
114
+ "Cn",
115
+ "Nh",
116
+ "Fl",
117
+ "Mc",
118
+ "Lv",
119
+ "Ts",
120
+ "Og"
121
+ ]);
122
+
123
+ // src/teaching-math.ts
124
+ function finite(value, name) {
125
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
126
+ }
127
+ function finiteValues(values, name) {
128
+ values.forEach((value) => finite(value, name));
129
+ }
130
+ function seededRandom(seed) {
131
+ if (!Number.isSafeInteger(seed)) throw new Error("Random seed must be a safe integer");
132
+ let state = seed >>> 0;
133
+ return () => {
134
+ state = state + 1831565813 >>> 0;
135
+ let value = Math.imul(state ^ state >>> 15, 1 | state);
136
+ value ^= value + Math.imul(value ^ value >>> 7, 61 | value);
137
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
138
+ };
139
+ }
140
+ function lerpArray(from, to, progress) {
141
+ if (from.length !== to.length) throw new Error("Interpolation vectors must have equal lengths");
142
+ finite(progress, "Interpolation progress");
143
+ finiteValues(from, "Interpolation value");
144
+ finiteValues(to, "Interpolation value");
145
+ const result = from.map((value, index) => {
146
+ const end = to[index];
147
+ const blended = value * (1 - progress) + end * progress;
148
+ if (Number.isFinite(blended)) return blended;
149
+ const scale = Math.max(Math.abs(value), Math.abs(end));
150
+ return (value / scale + (end / scale - value / scale) * progress) * scale;
151
+ });
152
+ finiteValues(result, "Interpolation result");
153
+ return result;
154
+ }
155
+ function dotProduct(left, right) {
156
+ if (left.length !== right.length) throw new Error("Dot product vectors must have equal lengths");
157
+ finiteValues(left, "Dot product value");
158
+ finiteValues(right, "Dot product value");
159
+ const result = left.reduce((sum, value, index) => sum + value * right[index], 0);
160
+ finite(result, "Dot product result");
161
+ return result;
162
+ }
163
+ function matrixWidth(matrix, name) {
164
+ const width = matrix[0]?.length ?? 0;
165
+ for (const row of matrix) {
166
+ if (row.length !== width) throw new Error(`${name} rows must be rectangular`);
167
+ finiteValues(row, `${name} value`);
168
+ }
169
+ return width;
170
+ }
171
+ function multiplyMatrices(left, right) {
172
+ const inner = matrixWidth(left, "Left matrix");
173
+ const columns = matrixWidth(right, "Right matrix");
174
+ if (inner !== right.length) throw new Error("Matrix inner dimensions must match");
175
+ return left.map((row) => Array.from({ length: columns }, (_, column) => {
176
+ const result = row.reduce((sum, value, index) => sum + value * right[index][column], 0);
177
+ finite(result, "Matrix product value");
178
+ return result;
179
+ }));
180
+ }
181
+ function stableSoftmax(values, temperature = 1) {
182
+ finite(temperature, "Softmax temperature");
183
+ if (temperature <= 0) throw new Error("Softmax temperature must be positive");
184
+ finiteValues(values, "Softmax logit");
185
+ if (!values.length) return [];
186
+ const maximum = values.reduce((largest, value) => Math.max(largest, value), -Infinity);
187
+ const weights = values.map((value) => Math.exp((value - maximum) / temperature));
188
+ const total = weights.reduce((sum, value) => sum + value, 0);
189
+ return weights.map((value) => value / total);
190
+ }
191
+ function combineSoftmaxMass(tiles, reference) {
192
+ if (reference !== void 0) finite(reference, "Softmax reference");
193
+ let largest = -Infinity;
194
+ for (const tile of tiles) {
195
+ if (tile.mass === 0 && tile.weightedSum === 0 && tile.reference === -Infinity) continue;
196
+ finite(tile.reference, "Tile reference");
197
+ finite(tile.mass, "Tile mass");
198
+ finite(tile.weightedSum, "Tile weighted sum");
199
+ if (tile.mass <= 0) throw new Error("A nonempty tile needs positive mass");
200
+ largest = Math.max(largest, tile.reference);
201
+ }
202
+ if (largest === -Infinity) return { reference: -Infinity, mass: 0, weightedSum: 0 };
203
+ const target = reference ?? largest;
204
+ if (target < largest) throw new Error("Softmax reference must cover all nonempty tiles");
205
+ let mass = 0, weightedSum = 0;
206
+ for (const tile of tiles) {
207
+ if (tile.mass === 0) continue;
208
+ const scale = Math.exp(tile.reference - target);
209
+ mass += scale * tile.mass;
210
+ weightedSum += scale * tile.weightedSum;
211
+ }
212
+ finite(mass, "Combined mass");
213
+ finite(weightedSum, "Combined weighted sum");
214
+ if (mass < 2 ** -1022) throw new Error("Combined mass is too small at this reference");
215
+ return { reference: target, mass, weightedSum };
216
+ }
217
+ function softmaxTileMass(scores, values, allowed) {
218
+ if (scores.length !== values.length || allowed !== void 0 && allowed.length !== scores.length) {
219
+ throw new Error("Scores, values and mask must have equal lengths");
220
+ }
221
+ const terms = [];
222
+ for (let i = 0; i < scores.length; i++) {
223
+ finite(scores[i], "Softmax score");
224
+ finite(values[i], "Softmax value");
225
+ if (allowed !== void 0 && typeof allowed[i] !== "boolean") throw new Error("Softmax mask entries must be booleans");
226
+ if (allowed?.[i] !== false) terms.push({ reference: scores[i], mass: 1, weightedSum: values[i] });
227
+ }
228
+ return combineSoftmaxMass(terms);
229
+ }
230
+ function entropy(probabilities, base = 2) {
231
+ finite(base, "Entropy base");
232
+ if (base <= 0 || base === 1) throw new Error("Entropy base must be positive and different from one");
233
+ finiteValues(probabilities, "Entropy probability");
234
+ if (!probabilities.length) return 0;
235
+ if (probabilities.some((value) => value < 0 || value > 1)) {
236
+ throw new Error("Entropy probabilities must lie between zero and one");
237
+ }
238
+ const total = probabilities.reduce((sum, value) => sum + value, 0);
239
+ if (Math.abs(total - 1) > 1e-9) throw new Error("Entropy probabilities must sum to one");
240
+ return -probabilities.reduce((sum, value) => value === 0 ? sum : sum + value * Math.log(value), 0) / Math.log(base);
241
+ }
242
+ function normalizeVector(values) {
243
+ finiteValues(values, "Vector value");
244
+ const scale = values.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0);
245
+ if (scale === 0) return values.map(() => 0);
246
+ const scaled = values.map((value) => value / scale);
247
+ const length = Math.sqrt(scaled.reduce((sum, value) => sum + value * value, 0));
248
+ return scaled.map((value) => value / length);
249
+ }
250
+ function sampleFunction(fn, low, high, count = 100) {
251
+ finite(low, "Sample domain start");
252
+ finite(high, "Sample domain end");
253
+ if (high <= low) throw new Error("Sample domain must increase");
254
+ if (!Number.isSafeInteger(count) || count < 2) throw new Error("Sample count must be an integer of at least two");
255
+ return Array.from({ length: count }, (_, index) => {
256
+ const amount = index / (count - 1);
257
+ const x = low * (1 - amount) + high * amount;
258
+ const y = fn(x);
259
+ finite(y, "Sampled function value");
260
+ return { x, y };
261
+ });
262
+ }
263
+ function gaussian(mean, sigma, x) {
264
+ finite(mean, "Gaussian mean");
265
+ finite(sigma, "Gaussian standard deviation");
266
+ finite(x, "Gaussian x");
267
+ if (sigma <= 0) throw new Error("Gaussian standard deviation must be positive");
268
+ const z = (x - mean) / sigma;
269
+ const density = Math.exp(-0.5 * z * z) / sigma / Math.sqrt(2 * Math.PI);
270
+ finite(density, "Gaussian density");
271
+ return density;
272
+ }
273
+ function sampleGaussian(random) {
274
+ const first = random();
275
+ const second = random();
276
+ if (!Number.isFinite(first) || !Number.isFinite(second) || first < 0 || first >= 1 || second < 0 || second >= 1) {
277
+ throw new Error("Gaussian random draws must lie in [0, 1)");
278
+ }
279
+ return Math.sqrt(-2 * Math.log(1 - first)) * Math.cos(2 * Math.PI * second);
280
+ }
281
+
282
+ export {
283
+ ELEMENT_SYMBOLS,
284
+ seededRandom,
285
+ lerpArray,
286
+ dotProduct,
287
+ multiplyMatrices,
288
+ stableSoftmax,
289
+ combineSoftmaxMass,
290
+ softmaxTileMass,
291
+ entropy,
292
+ normalizeVector,
293
+ sampleFunction,
294
+ gaussian,
295
+ sampleGaussian
296
+ };
@@ -0,0 +1 @@
1
+ import parseCssColor from"parse-css-color";import{liteAdaptor}from"mathjax-full/js/adaptors/liteAdaptor.js";import{RegisterHTMLHandler}from"mathjax-full/js/handlers/html.js";import{TeX}from"mathjax-full/js/input/tex.js";import"mathjax-full/js/input/tex/ams/AmsConfiguration.js";import"mathjax-full/js/input/tex/newcommand/NewcommandConfiguration.js";import"mathjax-full/js/input/tex/mhchem/MhchemConfiguration.js";import{STATE}from"mathjax-full/js/core/MathItem.js";import{mathjax}from"mathjax-full/js/mathjax.js";import{SVG}from"mathjax-full/js/output/svg.js";var DEFAULT_FONT_SIZE=16;var EX_FACTOR=.5;var adaptor=liteAdaptor({fontSize:DEFAULT_FONT_SIZE});RegisterHTMLHandler(adaptor);var outputJax=new SVG({fontCache:"none",exFactor:EX_FACTOR});var renderCache=new Map;var RENDER_CACHE_LIMIT=128;function createDocument(){const inputJax=new TeX({packages:["base","ams","newcommand","mhchem"],formatError(_jax,error){throw new Error(`Invalid TeX: ${error.message}`,{cause:error})}});inputJax.postFilters.add(({data})=>{data.root.walkTree(node=>{if(["munder","mover","munderover"].includes(node.kind)){node.attributes.set("data-vizmatic-kind",node.kind);node.childNodes.forEach((child,index)=>{child.attributes.set("data-vizmatic-slot",index)})}})},-4.5);return mathjax.document("",{InputJax:inputJax,OutputJax:outputJax})}function parseEx(value,name){if(typeof value!=="string"||!value.endsWith("ex")){throw new Error(`MathJax returned an unsupported ${name} dimension`)}const amount=Number(value.slice(0,-2));if(!Number.isFinite(amount)||amount<=0){throw new Error(`MathJax returned an invalid ${name} dimension`)}return amount}function parseViewBox(value){if(typeof value!=="string")throw new Error("MathJax returned an SVG without a viewBox");const values=value.trim().split(/[ ,]+/).map(Number);if(values.length!==4||values.some(part=>!Number.isFinite(part))||values[2]<=0||values[3]<=0){throw new Error("MathJax returned an invalid SVG viewBox")}return[values[0],values[1],values[2],values[3]]}function renderMathSvg(tex,options={}){return renderSvg(tex,options)}function renderMathFragmentSvg(source,fragment,options={}){return renderSvg(fragment,options,source===fragment?void 0:source)}function renderSvg(tex,options,context){if(typeof tex!=="string"||tex.trim().length===0){throw new Error("TeX input must be a non-empty string")}const fontSize=options.fontSize??DEFAULT_FONT_SIZE;if(!Number.isFinite(fontSize)||fontSize<=0){throw new Error("Math SVG fontSize must be a positive finite number")}const color=options.color??"#000000";if(typeof color!=="string"||!parseCssColor(color.trim())){throw new Error("Math SVG color must be a valid CSS color")}const normalizedColor=color.trim();const display=options.display??false;const key=JSON.stringify([tex,fontSize,normalizedColor,display,context]);const cached=renderCache.get(key);if(cached){renderCache.delete(key);renderCache.set(key,cached);return{...cached}}let container;try{const document=createDocument();if(context!==void 0)document.convert(context,{display,end:STATE.COMPILED});container=document.convert(tex,{display,em:fontSize,ex:fontSize*EX_FACTOR,containerWidth:fontSize*80})}catch(cause){if(cause instanceof Error&&cause.message.startsWith("Invalid TeX:"))throw cause;const detail=cause instanceof Error?cause.message:String(cause);throw new Error(`Unable to render TeX: ${detail}`,{cause})}const svgElement=adaptor.tags(container,"svg")[0];if(!svgElement)throw new Error("MathJax did not produce an SVG image");const width=parseEx(adaptor.getAttribute(svgElement,"width"),"width")*fontSize*EX_FACTOR;const height=parseEx(adaptor.getAttribute(svgElement,"height"),"height")*fontSize*EX_FACTOR;if(!Number.isFinite(width)||!Number.isFinite(height)){throw new Error("MathJax returned non-finite SVG dimensions")}const[,viewBoxY,,viewBoxHeight]=parseViewBox(adaptor.getAttribute(svgElement,"viewBox"));const baseline=-viewBoxY*height/viewBoxHeight;if(!Number.isFinite(baseline)){throw new Error("MathJax returned an invalid SVG baseline")}const drawing=adaptor.tags(svgElement,"g")[0];if(!drawing)throw new Error("MathJax returned an SVG without a drawing group");adaptor.removeAttribute(svgElement,"style");adaptor.setAttribute(svgElement,"width",`${width}px`);adaptor.setAttribute(svgElement,"height",`${height}px`);adaptor.setAttribute(drawing,"fill",normalizedColor);adaptor.setAttribute(drawing,"stroke",normalizedColor);const result={svg:adaptor.serializeXML(svgElement),width,height,baseline};renderCache.set(key,result);if(renderCache.size>RENDER_CACHE_LIMIT){renderCache.delete(renderCache.keys().next().value)}return{...result}}export{renderMathSvg,renderMathFragmentSvg};