matsci-parse 0.7.3 → 0.7.5

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../lib/core/matrix/matrix.ts","../lib/core/lattice/lattice.ts","../lib/core/structure/json.ts","../lib/core/structure/operations/canonicalize.ts","../lib/core/structure/operations/hashStructure.ts","../lib/core/structure/operations/sites/appendSite.ts","../lib/core/structure/operations/sites/insertSite.ts","../lib/core/structure/operations/sites/removeSite.ts","../lib/core/structure/operations/sites/replaceSite.ts","../lib/core/matrix/operations/vector/dot.ts","../lib/core/matrix/operations/vector/norm.ts","../lib/core/lattice/angles.ts","../lib/core/matrix/operations/inverse/inverse3x3.ts","../lib/core/lattice/inverse.ts","../lib/core/lattice/lengths.ts","../lib/core/matrix/operations/transpose.ts","../lib/core/matrix/operations/mul.ts","../lib/core/lattice/metricTensor.ts","../lib/core/lattice/parameters.ts","../lib/core/lattice/reciprocalLattice.ts","../lib/core/lattice/reciprocalLatticeCrystallographic.ts","../lib/core/matrix/operations/determinant.ts","../lib/core/lattice/volume.ts","../lib/core/lattice/create/fromParameters.ts","../lib/core/lattice/create/cubic.ts","../lib/core/lattice/create/hexagonal.ts","../lib/core/lattice/create/monoclinic.ts","../lib/core/lattice/create/orthorhombic.ts","../lib/core/lattice/create/rhombohedral.ts","../lib/core/lattice/create/tetragonal.ts","../lib/core/structure/operations/symmetry/spglib.ts","../lib/core/structure/operations/supercell.ts","../lib/core/site/site.ts","../lib/core/site/cartesian.ts","../lib/core/site/fractional.ts","../lib/core/site/distance.ts","../lib/core/site/wrap.ts","../lib/core/species/species.ts","../lib/core/io/cif.ts","../lib/core/io/poscar.ts","../lib/core/io/structuredata.ts","../lib/core/io/xsf.ts","../lib/core/io/xyz.ts"],"sourcesContent":["export interface Matrix {\n readonly rows: number;\n readonly cols: number;\n readonly data: Float64Array;\n}\n\nexport function createMatrix(\n rows: number,\n cols: number,\n data?: Iterable<number>,\n): Matrix {\n const size = rows * cols;\n\n const buffer = data ? Float64Array.from(data) : new Float64Array(size);\n\n if (buffer.length !== size) {\n throw new Error(`Expected ${size} values, got ${buffer.length}`);\n }\n\n return {\n rows,\n cols,\n data: buffer,\n };\n}\n\nexport function identity(size: number): Matrix {\n const data = new Float64Array(size * size);\n\n for (let i = 0; i < size; i++) {\n data[i * size + i] = 1;\n }\n\n return {\n rows: size,\n cols: size,\n data,\n };\n}\n\nexport function clone(matrix: Matrix): Matrix {\n return {\n rows: matrix.rows,\n cols: matrix.cols,\n data: new Float64Array(matrix.data),\n };\n}\n\nexport function index(cols: number, row: number, col: number): number {\n return row * cols + col;\n}\n","import { createMatrix, Matrix } from \"../matrix/matrix\";\n\nconst EPS = 1e-12;\n\nfunction clean(x: number): number {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\nexport interface Lattice {\n readonly basis: Matrix;\n}\n\nexport function createLattice(data: number[] | Matrix): Lattice {\n const values = \"data\" in data ? data.data : data;\n\n if (values.length !== 9) {\n throw new Error(\"Lattice requires 9 values (3x3)\");\n }\n\n const cleaned = new Float64Array(9);\n\n for (let i = 0; i < 9; i++) {\n cleaned[i] = clean(values[i]);\n }\n\n return {\n basis: createMatrix(3, 3, cleaned),\n };\n}\n","import { Structure } from \"./structure\";\nimport { createLattice } from \"../lattice/lattice\";\n\nexport function toJSON(structure: Structure) {\n return {\n lattice: structure.lattice.basis.data,\n sites: structure.sites.map((s) => ({\n species: s.species,\n frac: Array.from(s.frac),\n })),\n };\n}\n\nexport function fromJSON(data: any): Structure {\n return {\n lattice: createLattice(data.lattice),\n sites: data.sites.map((s: any) => ({\n species: s.species,\n frac: new Float64Array(s.frac),\n })),\n };\n}\n","import { Structure } from \"../../structure/structure\";\n\nconst EPS = 1e-12;\n\nfunction wrap(x: number): number {\n const v = x - Math.floor(x);\n return Math.abs(v) < EPS ? 0 : v;\n}\n\nfunction clean(x: number): number {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\nexport function canonicalize(structure: Structure): Structure {\n return {\n ...structure,\n sites: structure.sites.map((site) => ({\n ...site,\n frac: new Float64Array([\n wrap(clean(site.frac[0])),\n wrap(clean(site.frac[1])),\n wrap(clean(site.frac[2])),\n ]),\n })),\n };\n}\n","import { Structure } from \"../structure\";\nimport { canonicalize } from \"./canonicalize\";\n\nfunction toFixedArray(v: Float64Array, precision = 8): string {\n return Array.from(v)\n .map((x) => x.toFixed(precision))\n .join(\",\");\n}\n\nfunction fnv1a(str: string): number {\n let hash = 2166136261;\n\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash *= 16777619;\n }\n\n return hash >>> 0;\n}\n\nexport function hashStructure(structure: Structure): number {\n const s = canonicalize(structure);\n\n const lattice = s.lattice.basis.data;\n const latticeKey = toFixedArray(lattice);\n\n const sitesKey = s.sites\n .map((site) => {\n return site.species + \":\" + toFixedArray(site.frac);\n })\n .sort()\n .join(\"|\");\n\n const key = latticeKey + \"::\" + sitesKey;\n\n return fnv1a(key);\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\nexport function appendSite(structure: Structure, site: Site): Structure {\n return {\n ...structure,\n sites: [...structure.sites, site],\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\nexport function insertSite(\n structure: Structure,\n index: number,\n site: Site,\n): Structure {\n return {\n ...structure,\n sites: [\n ...structure.sites.slice(0, index),\n site,\n ...structure.sites.slice(index),\n ],\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\nexport function removeSite(structure: Structure, index: number): Structure {\n return {\n ...structure,\n sites: structure.sites.filter((_, i) => i !== index),\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\nexport function replaceSite(\n structure: Structure,\n index: number,\n site: Site,\n): Structure {\n return {\n ...structure,\n sites: structure.sites.map((s, i) => (i === index ? site : s)),\n };\n}\n","import { Vector } from \"../../vector\";\n\nexport function dot(a: Vector, b: Vector): number {\n if (a.length !== b.length) {\n throw new Error(\"Dot product requires same-length vectors\");\n }\n\n let sum = 0;\n\n for (let i = 0; i < a.length; i++) {\n sum += a[i] * b[i];\n }\n\n return sum;\n}\n","import { Vector } from \"../../vector\";\n\nconst EPS = 1e-12;\n\nexport function norm(v: Vector): number {\n let sum = 0;\n\n for (let i = 0; i < v.length; i++) {\n const x = v[i];\n sum += x * x;\n }\n\n return Math.sqrt(sum);\n}\n","import { dot } from \"../matrix/operations/vector/dot\";\nimport { norm } from \"../matrix/operations/vector/norm\";\nimport { Lattice } from \"./lattice\";\n\nfunction angle(u: number[], v: number[]) {\n const denom = norm(u) * norm(v);\n if (denom === 0) throw new Error(\"Zero-length lattice vector\");\n\n const c = dot(u, v) / denom;\n const clamped = Math.max(-1, Math.min(1, c));\n\n return Math.acos(clamped);\n}\n\nexport function angles(lattice: Lattice): [number, number, number] {\n const m = lattice.basis.data;\n\n const a = [m[0], m[1], m[2]];\n const b = [m[3], m[4], m[5]];\n const c = [m[6], m[7], m[8]];\n\n const alpha = angle(b, c);\n const beta = angle(a, c);\n const gamma = angle(a, b);\n\n return [alpha, beta, gamma];\n}\n","import { Matrix, createMatrix } from \"../../matrix\";\n\nexport function inverse3x3(m: Matrix): Matrix {\n if (m.rows !== 3 || m.cols !== 3) {\n throw new Error(\"Expected 3x3 matrix\");\n }\n\n const a00 = m.data[0],\n a01 = m.data[1],\n a02 = m.data[2];\n const a10 = m.data[3],\n a11 = m.data[4],\n a12 = m.data[5];\n const a20 = m.data[6],\n a21 = m.data[7],\n a22 = m.data[8];\n\n const c00 = a11 * a22 - a12 * a21;\n const c01 = a12 * a20 - a10 * a22;\n const c02 = a10 * a21 - a11 * a20;\n\n const c10 = a02 * a21 - a01 * a22;\n const c11 = a00 * a22 - a02 * a20;\n const c12 = a01 * a20 - a00 * a21;\n\n const c20 = a01 * a12 - a02 * a11;\n const c21 = a02 * a10 - a00 * a12;\n const c22 = a00 * a11 - a01 * a10;\n\n const det = a00 * c00 + a01 * c01 + a02 * c02;\n\n if (det === 0) {\n throw new Error(\"Singular matrix\");\n }\n\n const invDet = 1 / det;\n\n const out = createMatrix(3, 3);\n\n out.data[0] = c00 * invDet;\n out.data[1] = c10 * invDet;\n out.data[2] = c20 * invDet;\n\n out.data[3] = c01 * invDet;\n out.data[4] = c11 * invDet;\n out.data[5] = c21 * invDet;\n\n out.data[6] = c02 * invDet;\n out.data[7] = c12 * invDet;\n out.data[8] = c22 * invDet;\n\n return out;\n}\n","import { Lattice } from \"./lattice\";\nimport { inverse3x3 } from \"../matrix/operations/inverse/inverse3x3\";\nimport { Matrix } from \"../matrix/matrix\";\n\nexport function inverse(lattice: Lattice): Matrix {\n return inverse3x3(lattice.basis);\n}\n","import { norm } from \"../matrix/operations/vector/norm\";\nimport { Lattice } from \"./lattice\";\n\nexport function lengths(lattice: Lattice): [number, number, number] {\n const m = lattice.basis.data;\n\n const a: Float64Array = new Float64Array([m[0], m[1], m[2]]);\n const b: Float64Array = new Float64Array([m[3], m[4], m[5]]);\n const c: Float64Array = new Float64Array([m[6], m[7], m[8]]);\n\n return [norm(a), norm(b), norm(c)];\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\nexport function transpose(matrix: Matrix): Matrix {\n const out = createMatrix(matrix.cols, matrix.rows);\n\n for (let row = 0; row < matrix.rows; row++) {\n for (let col = 0; col < matrix.cols; col++) {\n out.data[index(out.cols, col, row)] =\n matrix.data[index(matrix.cols, row, col)];\n }\n }\n\n return out;\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\nexport function mul(a: Matrix, b: Matrix): Matrix {\n if (a.cols !== b.rows) {\n throw new Error(\"Invalid matrix multiplication dimensions\");\n }\n\n const out = createMatrix(a.rows, b.cols);\n\n const aRows = a.rows;\n const aCols = a.cols;\n const bCols = b.cols;\n\n for (let row = 0; row < aRows; row++) {\n for (let col = 0; col < bCols; col++) {\n let sum = 0;\n\n for (let k = 0; k < aCols; k++) {\n sum += a.data[index(a.cols, row, k)] * b.data[index(b.cols, k, col)];\n }\n\n out.data[index(out.cols, row, col)] = sum;\n }\n }\n\n return out;\n}\n","import { transpose } from \"../matrix/operations/transpose\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { Lattice } from \"./lattice\";\nimport { Matrix } from \"../matrix/matrix\";\n\nexport function metricTensor(lattice: Lattice): Matrix {\n const A = lattice.basis;\n\n const AT = transpose(A);\n return mul(AT, A);\n}\n","import { lengths } from \"./lengths\";\nimport { angles } from \"./angles\";\nimport { Lattice } from \"./lattice\";\n\nconst RAD2DEG = 180 / Math.PI;\n\nexport function parameters(\n lattice: Lattice,\n): [number, number, number, number, number, number] {\n const [a, b, c] = lengths(lattice);\n const [alpha, beta, gamma] = angles(lattice);\n\n return [a, b, c, alpha * RAD2DEG, beta * RAD2DEG, gamma * RAD2DEG];\n}\n","import { Lattice } from \"./lattice\";\nimport { inverse } from \"./inverse\";\nimport { transpose } from \"../matrix/operations/transpose\";\nimport { createMatrix } from \"../matrix/matrix\";\nimport { createLattice } from \"./lattice\";\n\nconst TWO_PI = 2 * Math.PI;\n\nexport function reciprocalLattice(lattice: Lattice): Lattice {\n const inv = inverse(lattice);\n const invT = transpose(inv);\n\n const data = invT.data.map((v) => v * TWO_PI);\n\n return createLattice(data);\n}\n","import { Lattice, createLattice } from \"./lattice\";\nimport { inverse } from \"./inverse\";\nimport { transpose } from \"../matrix/operations/transpose\";\n\nexport function reciprocalLatticeCrystallographic(lattice: Lattice): Lattice {\n const inv = inverse(lattice);\n const invT = transpose(inv);\n\n return createLattice(invT.data);\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\nfunction minor(matrix: Matrix, skipRow: number, skipCol: number): Matrix {\n const out = createMatrix(matrix.rows - 1, matrix.cols - 1);\n\n let ptr = 0;\n\n for (let row = 0; row < matrix.rows; row++) {\n if (row === skipRow) continue;\n\n for (let col = 0; col < matrix.cols; col++) {\n if (col === skipCol) continue;\n\n out.data[ptr++] = matrix.data[index(matrix.cols, row, col)];\n }\n }\n\n return out;\n}\n\nexport function determinant(matrix: Matrix): number {\n if (matrix.rows !== matrix.cols) {\n throw new Error(\"Determinant requires a square matrix\");\n }\n\n const n = matrix.rows;\n\n if (n === 1) {\n return matrix.data[0];\n }\n\n if (n === 2) {\n return matrix.data[0] * matrix.data[3] - matrix.data[1] * matrix.data[2];\n }\n\n let det = 0;\n\n for (let col = 0; col < n; col++) {\n const sign = col % 2 === 0 ? 1 : -1;\n\n det += sign * matrix.data[col] * determinant(minor(matrix, 0, col));\n }\n\n return det;\n}\n","import { determinant } from \"../matrix/operations/determinant\";\nimport { Lattice } from \"./lattice\";\n\nexport function volume(lattice: Lattice): number {\n return Math.abs(determinant(lattice.basis));\n}\n","import { createLattice } from \"../lattice\";\n\nconst DEG2RAD = Math.PI / 180;\nconst EPS = 1e-12;\n\nfunction clean(x: number) {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\nexport function fromParameters(\n a: number,\n b: number,\n c: number,\n alpha: number,\n beta: number,\n gamma: number,\n) {\n const alphaR = alpha * DEG2RAD;\n const betaR = beta * DEG2RAD;\n const gammaR = gamma * DEG2RAD;\n\n const cosA = Math.cos(alphaR);\n const cosB = Math.cos(betaR);\n const cosG = Math.cos(gammaR);\n const sinG = Math.sin(gammaR);\n\n // lattice vectors\n const v1 = [a, 0, 0];\n\n const v2 = [b * cosG, b * sinG, 0];\n\n // guard against degenerate gamma\n if (Math.abs(sinG) < EPS) {\n throw new Error(\"Invalid lattice: gamma too close to 0 or 180 degrees\");\n }\n\n const cx = c * cosB;\n\n const cy = (c * (cosA - cosB * cosG)) / sinG;\n\n const czSquared = c * c - cx * cx - cy * cy;\n\n const cz = Math.sqrt(Math.max(0, czSquared));\n\n return createLattice([\n clean(v1[0]),\n clean(v1[1]),\n clean(v1[2]),\n clean(v2[0]),\n clean(v2[1]),\n clean(v2[2]),\n clean(cx),\n clean(cy),\n clean(cz),\n ]);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function cubic(a: number) {\n return fromParameters(a, a, a, 90, 90, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function hexagonal(a: number, c: number) {\n return fromParameters(a, a, c, 90, 90, 120);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function monoclinic(a: number, b: number, c: number, beta: number) {\n return fromParameters(a, b, c, 90, beta, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function orthorhombic(a: number, b: number, c: number) {\n return fromParameters(a, b, c, 90, 90, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function rhombohedral(a: number, alpha: number) {\n return fromParameters(a, a, a, alpha, alpha, alpha);\n}\n","import { fromParameters } from \"./fromParameters\";\n\nexport function tetragonal(a: number, c: number) {\n return fromParameters(a, a, c, 90, 90, 90);\n}\n","import init, { analyze_cell, type MoyoDataset } from \"@spglib/moyo-wasm\";\n\nimport { createLattice } from \"@/core/lattice\";\nimport { Structure } from \"../../structure\";\n\nlet ready: Promise<void> | null = null;\n\n// Slightly awkward handling to manage node vs browser invocation (for tests...)\nexport function initMoyo() {\n if (!ready) {\n ready = (async () => {\n // In Node.js (tests), load from filesystem\n if (typeof process !== \"undefined\" && process.versions?.node) {\n try {\n const { readFileSync } = await import(\"fs\");\n const { join } = await import(\"path\");\n const wasmPath = join(\n process.cwd(),\n \"node_modules/@spglib/moyo-wasm/moyo_wasm_bg.wasm\",\n );\n const wasmBuffer = readFileSync(wasmPath);\n await init(wasmBuffer);\n } catch (e) {\n console.error(\"Failed to load WASM in Node:\", e);\n throw e;\n }\n } else {\n // In browser, use dynamic import to get the URL\n const wasmUrl = new URL(\n \"@spglib/moyo-wasm/moyo_wasm_bg.wasm\",\n import.meta.url,\n ).toString();\n\n await init(wasmUrl);\n }\n })();\n }\n return ready;\n}\n\nexport async function getSymmetry(\n structure: Structure,\n tolerance = 1e-4,\n setting = \"Standard\",\n): Promise<{\n primitive: Structure;\n conventional: Structure;\n calculationResults: any;\n}> {\n await initMoyo();\n\n // -----------------------------\n // 1. Build reversible mapping\n // -----------------------------\n const symbolToId = new Map<string, number>();\n const idToSymbol = new Map<number, string>();\n\n let counter = 0;\n\n const positions: number[][] = [];\n const numbers: number[] = [];\n\n for (const site of structure.sites) {\n const symbol = site.species.symbol;\n\n if (!symbolToId.has(symbol)) {\n symbolToId.set(symbol, counter);\n idToSymbol.set(counter, symbol);\n counter++;\n }\n\n positions.push(Array.from(site.frac));\n numbers.push(symbolToId.get(symbol)!);\n }\n\n // -----------------------------\n // 2. Build Moyo input\n // -----------------------------\n const moyoInput = {\n lattice: {\n basis: Array.from(structure.lattice.basis.data),\n },\n positions,\n numbers,\n };\n\n // -----------------------------\n // 3. Run symmetry engine\n // -----------------------------\n const results = await analyze_cell(\n JSON.stringify(moyoInput),\n tolerance,\n setting,\n );\n\n // -----------------------------\n // 4. Convert Moyo cell → Structure\n // -----------------------------\n function build(cell: any): Structure {\n const { lattice, positions, numbers } = cell;\n\n const species = [...new Set(numbers)].map((n: number) => ({\n symbol: idToSymbol.get(n)!,\n }));\n\n const sites = positions.map((pos: number[], i: number) => ({\n species: {\n symbol: idToSymbol.get(numbers[i])!,\n },\n frac: new Float64Array(pos),\n }));\n\n return {\n lattice: createLattice(lattice.basis),\n species,\n sites,\n };\n }\n\n // -----------------------------\n // 5. Return both structures\n // -----------------------------\n return {\n primitive: build(results.prim_std_cell),\n conventional: build(results.std_cell),\n calculationResults: results,\n };\n}\n","import { createLattice } from \"@/core/lattice/lattice\";\nimport type { Structure } from \"../structure\";\nimport type { Site } from \"@/core/site/site\";\n\ntype SupercellSize = number | [number, number, number];\n\nexport function supercell(\n structure: Structure,\n size: SupercellSize,\n): Structure {\n const [nx, ny, nz] = typeof size === \"number\" ? [size, size, size] : size;\n\n if (\n nx < 1 ||\n ny < 1 ||\n nz < 1 ||\n !Number.isInteger(nx) ||\n !Number.isInteger(ny) ||\n !Number.isInteger(nz)\n ) {\n throw new Error(\"Supercell dimensions must be positive integers\");\n }\n\n const m = structure.lattice.basis.data;\n\n // row-major scaling\n const newBasis = [\n m[0] * nx,\n m[1] * nx,\n m[2] * nx,\n\n m[3] * ny,\n m[4] * ny,\n m[5] * ny,\n\n m[6] * nz,\n m[7] * nz,\n m[8] * nz,\n ];\n\n const sites: Site[] = [];\n\n for (const site of structure.sites) {\n const [x, y, z] = site.frac;\n\n for (let i = 0; i < nx; i++) {\n for (let j = 0; j < ny; j++) {\n for (let k = 0; k < nz; k++) {\n sites.push({\n species: site.species,\n\n frac: new Float64Array([(x + i) / nx, (y + j) / ny, (z + k) / nz]),\n });\n }\n }\n }\n }\n\n return {\n lattice: createLattice(newBasis),\n sites,\n };\n}\n","import { Species } from \"../species/species\";\n\nexport type SiteProperties = Record<string, any>;\n\nexport type Site<P extends SiteProperties = SiteProperties> = {\n species: Species;\n frac: [number, number, number];\n properties?: P;\n};\n\nexport function createSite<P extends SiteProperties>(\n species: Species,\n frac: [number, number, number],\n properties?: P,\n): Site<P> {\n return {\n species,\n frac,\n properties,\n };\n}\n","import { mul } from \"../matrix/operations/mul\";\nimport { Site } from \"./site\";\nimport { Lattice } from \"../lattice/lattice\";\nimport { Vector } from \"../matrix/vector\";\nimport { Matrix } from \"@/math/matrix\";\n\nexport function cartesian(lattice: Lattice, site: Site): Vector {\n const [x, y, z] = site.frac;\n\n const frac = {\n rows: 3,\n cols: 1,\n data: new Float64Array([x, y, z]),\n };\n\n const result = mul(lattice.basis, frac);\n\n return new Float64Array([result.data[0], result.data[1], result.data[2]]);\n}\n","import { inverse } from \"../lattice/inverse\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { Vector } from \"../matrix/vector\";\nimport { Lattice } from \"../lattice/lattice\";\n\nexport function fractional(lattice: Lattice, cart: Vector): Vector {\n const vec = {\n rows: 3,\n cols: 1,\n data: cart,\n };\n\n const inv = inverse(lattice);\n\n const result = mul(inv, vec);\n\n return new Float64Array([result.data[0], result.data[1], result.data[2]]);\n}\n","import { Lattice } from \"../lattice/lattice\";\nimport { Site } from \"./site\";\nimport { cartesian } from \"./cartesian\";\n\nimport { norm } from \"../matrix/operations/vector/norm\";\n\nexport function distance(lattice: Lattice, a: Site, b: Site): number {\n const dFrac: [number, number, number] = [\n b.frac[0] - a.frac[0],\n b.frac[1] - a.frac[1],\n b.frac[2] - a.frac[2],\n ];\n\n for (let i = 0; i < 3; i++) {\n dFrac[i] -= Math.round(dFrac[i]);\n }\n\n const displaced: Site = {\n species: a.species,\n frac: dFrac,\n };\n\n const dCart = cartesian(lattice, displaced);\n\n return norm(dCart);\n}\n","import { Site } from \"./site\";\n\nfunction wrapValue(x: number): number {\n return ((x % 1) + 1) % 1;\n}\n\nexport function wrap<T>(site: Site<T>): Site<T> {\n return {\n ...site,\n frac: [\n wrapValue(site.frac[0]),\n wrapValue(site.frac[1]),\n wrapValue(site.frac[2]),\n ],\n };\n}\n","export type Species<P extends Record<string, any> = Record<string, any>> = {\n symbol: string;\n properties?: P;\n};\n\nexport function createSpecies<P extends Record<string, any>>(\n symbol: string,\n properties?: P,\n): Species<P> {\n return { symbol, properties };\n}\n","import { fromParameters } from \"../lattice/create/fromParameters\";\nimport { parameters } from \"../lattice/parameters\";\nimport { Structure } from \"../structure/structure\";\n\nfunction cleanValue(value: string): number {\n // remove uncertainty notation:\n // 5.432(1) -> 5.432\n return Number(value.replace(/\\(.+\\)/, \"\"));\n}\n\nfunction tokenize(line: string): string[] {\n return line.match(/'[^']*'|\"[^\"]*\"|\\S+/g) ?? [];\n}\n\nfunction warnUnsupportedSymmetry(spaceGroup: string) {\n console.warn(\n `Space group \"${spaceGroup}\" detected. ` +\n `Symmetry operations are not currently applied; ` +\n `only asymmetric-unit sites will be parsed.`,\n );\n}\n\nexport function fromCIF(text: string): Structure {\n const lines = text\n .split(\"\\n\")\n .map((x) => x.trim())\n .filter(Boolean);\n\n let a = 0;\n let b = 0;\n let c = 0;\n\n let alpha = 0;\n let beta = 0;\n let gamma = 0;\n\n let spaceGroup = \"P1\";\n\n let atomHeaders: string[] = [];\n const atomRows: string[][] = [];\n\n let inLoop = false;\n let currentHeaders: string[] = [];\n let collectingAtoms = false;\n\n for (const line of lines) {\n if (line.startsWith(\"_symmetry_space_group_name_H-M\")) {\n const tokens = tokenize(line);\n spaceGroup = tokens.at(-1)?.replace(/['\"]/g, \"\") ?? \"P1\";\n } else if (line.startsWith(\"_space_group_name_H-M_alt\")) {\n const tokens = tokenize(line);\n spaceGroup = tokens.at(-1)?.replace(/['\"]/g, \"\") ?? \"P1\";\n } else if (line.startsWith(\"_cell_length_a\")) {\n a = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_length_b\")) {\n b = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_length_c\")) {\n c = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_alpha\")) {\n alpha = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_beta\")) {\n beta = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_gamma\")) {\n gamma = cleanValue(tokenize(line)[1]);\n } else if (line === \"loop_\") {\n inLoop = true;\n currentHeaders = [];\n collectingAtoms = false;\n continue;\n }\n\n if (inLoop && line.startsWith(\"_\")) {\n currentHeaders.push(line);\n\n if (line.includes(\"_atom_site_\")) {\n collectingAtoms = true;\n }\n\n continue;\n }\n\n if (inLoop && collectingAtoms) {\n if (atomHeaders.length === 0) {\n atomHeaders = [...currentHeaders];\n }\n\n atomRows.push(tokenize(line));\n }\n }\n\n const isP1 = /^P\\s*1$/i.test(spaceGroup);\n\n if (!isP1) {\n warnUnsupportedSymmetry(spaceGroup);\n }\n\n const lattice = fromParameters(a, b, c, alpha, beta, gamma);\n\n const ix = atomHeaders.findIndex((x) => x.includes(\"fract_x\"));\n\n const iy = atomHeaders.findIndex((x) => x.includes(\"fract_y\"));\n\n const iz = atomHeaders.findIndex((x) => x.includes(\"fract_z\"));\n\n const ispecies = atomHeaders.findIndex((x) => x.includes(\"type_symbol\"));\n\n if (ix < 0 || iy < 0 || iz < 0 || ispecies < 0) {\n throw new Error(\"Missing required atom site columns\");\n }\n\n const sites = atomRows.map((row) => ({\n species: {\n symbol: row[ispecies],\n },\n\n frac: new Float64Array([\n cleanValue(row[ix]),\n cleanValue(row[iy]),\n cleanValue(row[iz]),\n ]),\n }));\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toCIF(structure: Structure, precision = 6): string {\n const p = parameters(structure.lattice);\n\n const lines: string[] = [];\n\n lines.push(\"data_matsci-parse\");\n lines.push(\"\");\n\n lines.push(\"_symmetry_space_group_name_H-M 'P 1'\");\n lines.push(\"_symmetry_Int_Tables_number 1\");\n\n lines.push(\"\");\n\n lines.push(`_cell_length_a ${p[0].toFixed(precision)}`);\n\n lines.push(`_cell_length_b ${p[1].toFixed(precision)}`);\n\n lines.push(`_cell_length_c ${p[2].toFixed(precision)}`);\n\n lines.push(`_cell_angle_alpha ${p[3].toFixed(precision)}`);\n\n lines.push(`_cell_angle_beta ${p[4].toFixed(precision)}`);\n\n lines.push(`_cell_angle_gamma ${p[5].toFixed(precision)}`);\n\n lines.push(\"\");\n\n lines.push(\"loop_\");\n lines.push(\"_atom_site_label\");\n lines.push(\"_atom_site_type_symbol\");\n lines.push(\"_atom_site_fract_x\");\n lines.push(\"_atom_site_fract_y\");\n lines.push(\"_atom_site_fract_z\");\n\n for (let i = 0; i < structure.sites.length; i++) {\n const site = structure.sites[i];\n\n lines.push(\n `${site.species.symbol}${i + 1} ` +\n `${site.species.symbol} ` +\n `${site.frac[0].toFixed(precision)} ` +\n `${site.frac[1].toFixed(precision)} ` +\n `${site.frac[2].toFixed(precision)}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","import { createLattice } from \"../lattice/lattice\";\nimport { inverse } from \"../lattice/inverse\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { createMatrix } from \"../matrix/matrix\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\nimport { fractional } from \"../site/fractional\";\n\nfunction isSelective(line: string): boolean {\n return line.toLowerCase().startsWith(\"selective\");\n}\n\nfunction isDirect(line: string): boolean {\n const l = line.toLowerCase();\n return l.startsWith(\"direct\") || l.startsWith(\"fractional\");\n}\n\nfunction isCartesian(line: string): boolean {\n const l = line.toLowerCase();\n return l.startsWith(\"cart\");\n}\n\n// TODO: Currently nukes the selective dynamics flag from the input file.\n// It would be good to restore this.\n// TODO: would be good to ensure that the title is also optionally\n// maintained.\nexport function fromPOSCAR(text: string): Structure {\n const lines = text\n .split(\"\\n\")\n .map((x) => x.trim())\n .filter(Boolean);\n\n let cursor = 0;\n\n // comment/title\n cursor++;\n\n // scale factor\n const scale = Number(lines[cursor++]);\n\n // lattice vectors (row-major)\n const latticeData: number[] = [];\n\n for (let i = 0; i < 3; i++) {\n const v = lines[cursor++].split(/\\s+/).map(Number);\n\n if (v.length !== 3) {\n throw new Error(\"Invalid POSCAR lattice\");\n }\n\n latticeData.push(v[0] * scale, v[1] * scale, v[2] * scale);\n }\n\n const lattice = createLattice(latticeData);\n\n // VASP5 species names\n const symbols = lines[cursor++].split(/\\s+/);\n\n // atom counts\n const counts = lines[cursor++].split(/\\s+/).map(Number);\n\n if (symbols.length !== counts.length) {\n throw new Error(\"Species/count mismatch\");\n }\n\n // optional selective dynamics\n if (isSelective(lines[cursor])) {\n cursor++;\n }\n\n const direct = isDirect(lines[cursor]);\n const cartesian = isCartesian(lines[cursor]);\n\n if (!direct && !cartesian) {\n throw new Error(\"Expected Direct or Cartesian\");\n }\n\n cursor++;\n\n const sites: Site[] = [];\n\n let speciesIndex = 0;\n let remaining = counts[0];\n\n const latticeInv = cartesian ? inverse(lattice) : null;\n\n const totalAtoms = counts.reduce((a, b) => a + b, 0);\n\n for (let i = 0; i < totalAtoms; i++) {\n const tokens = lines[cursor++].split(/\\s+/);\n\n const coords = tokens.slice(0, 3).map(Number);\n\n const frac = direct\n ? new Float64Array(coords)\n : fractional(lattice, new Float64Array(coords));\n\n sites.push({\n species: {\n symbol: symbols[speciesIndex],\n },\n frac,\n });\n\n remaining--;\n\n if (remaining === 0 && speciesIndex < counts.length - 1) {\n speciesIndex++;\n remaining = counts[speciesIndex];\n }\n }\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toPOSCAR(\n structure: Structure,\n options?: {\n title?: string;\n scale?: number;\n direct?: boolean;\n },\n): string {\n const title = options?.title ?? \"Generated by matsci-parse\";\n const scale = options?.scale ?? 1.0;\n const direct = options?.direct ?? true;\n\n const lines: string[] = [];\n\n lines.push(title);\n lines.push(String(scale));\n\n // lattice\n const m = structure.lattice.basis.data;\n\n lines.push(`${m[0]} ${m[1]} ${m[2]}`);\n lines.push(`${m[3]} ${m[4]} ${m[5]}`);\n lines.push(`${m[6]} ${m[7]} ${m[8]}`);\n\n // preserve order of first appearance\n const grouped = new Map<string, typeof structure.sites>();\n\n for (const site of structure.sites) {\n const symbol = site.species.symbol;\n\n if (!grouped.has(symbol)) {\n grouped.set(symbol, []);\n }\n\n grouped.get(symbol)!.push(site);\n }\n\n const species = [...grouped.keys()];\n const sites = [...grouped.values()].flat();\n\n lines.push(species.join(\" \"));\n lines.push(species.map((s) => grouped.get(s)!.length).join(\" \"));\n\n lines.push(direct ? \"Direct\" : \"Cartesian\");\n\n for (const site of sites) {\n const coords = direct ? site.frac : cartesian(structure.lattice, site);\n\n lines.push(`${coords[0]} ${coords[1]} ${coords[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import { Structure } from \"../structure/structure\";\nimport { createLattice } from \"../lattice/lattice\";\n\nimport { cartesian } from \"../site/cartesian\";\nimport { fractional } from \"../site/fractional\";\n\nexport interface AiiDASite {\n position: [number, number, number];\n symbols: string[];\n}\n\nexport interface StructureData {\n cell: [\n [number, number, number],\n [number, number, number],\n [number, number, number],\n ];\n\n sites: AiiDASite[];\n}\n\nexport function fromStructureData(data: any): Structure {\n const lattice = createLattice([\n ...data.cell[0],\n ...data.cell[1],\n ...data.cell[2],\n ]);\n\n const kindMap = new Map(data.kinds.map((kind: any) => [kind.name, kind]));\n\n const sites = data.sites.map((site: any) => {\n const kind = kindMap.get(site.kind_name);\n\n if (!kind) {\n throw new Error(`Unknown kind \"${site.kind_name}\"`);\n }\n\n return {\n species: {\n symbol: kind.symbols[0],\n },\n\n frac: fractional(lattice, new Float64Array(site.position)),\n };\n });\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toStructureData(structure: Structure) {\n const m = structure.lattice.basis.data;\n\n const symbols = [...new Set(structure.sites.map((s) => s.species.symbol))];\n\n const kinds = symbols.map((symbol) => ({\n name: symbol,\n symbols: [symbol],\n }));\n\n return {\n cell: [\n [m[0], m[1], m[2]],\n [m[3], m[4], m[5]],\n [m[6], m[7], m[8]],\n ],\n\n kinds,\n\n sites: structure.sites.map((site) => ({\n kind_name: site.species.symbol,\n\n position: Array.from(cartesian(structure.lattice, site)),\n })),\n\n pbc1: true,\n pbc2: true,\n pbc3: true,\n };\n}\n","import { createLattice } from \"../lattice/lattice\";\nimport { fractional } from \"../site/fractional\";\nimport { cartesian } from \"../site/cartesian\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\n\nfunction findSection(lines: string[], section: string): number {\n const idx = lines.findIndex((line) => line.trim().toUpperCase() === section);\n\n if (idx === -1) {\n throw new Error(`Missing ${section}`);\n }\n\n return idx;\n}\n\n// TODO: support atomic numbers instead of symbols in primvec.\n\nexport function fromXSF(text: string): Structure {\n const lines = text\n .split(\"\\n\")\n .map((x) => x.trim())\n .filter(Boolean);\n\n const vecStart = findSection(lines, \"PRIMVEC\");\n\n const lattice = createLattice([\n ...lines[vecStart + 1].split(/\\s+/).map(Number),\n ...lines[vecStart + 2].split(/\\s+/).map(Number),\n ...lines[vecStart + 3].split(/\\s+/).map(Number),\n ]);\n\n const coordStart = findSection(lines, \"PRIMCOORD\");\n\n const [nAtoms] = lines[coordStart + 1].split(/\\s+/).map(Number);\n\n const sites: Site[] = [];\n\n for (let i = 0; i < nAtoms; i++) {\n const tokens = lines[coordStart + 2 + i].split(/\\s+/);\n\n const symbol = tokens[0];\n\n const x = Number(tokens[1]);\n const y = Number(tokens[2]);\n const z = Number(tokens[3]);\n\n const frac = fractional(lattice, new Float64Array([x, y, z]));\n\n sites.push({\n species: { symbol },\n frac,\n });\n }\n\n return {\n lattice,\n sites,\n };\n}\n\nfunction formatVec(v: number[]): string {\n return `${v[0]} ${v[1]} ${v[2]}`;\n}\n\nfunction formatLattice(lattice: Structure[\"lattice\"]): string[] {\n const m = lattice.basis.data;\n\n return [\n formatVec([m[0], m[1], m[2]]),\n formatVec([m[3], m[4], m[5]]),\n formatVec([m[6], m[7], m[8]]),\n ];\n}\n\nexport function toXSF(structure: Structure): string {\n const lines: string[] = [];\n\n lines.push(\"CRYSTAL\");\n lines.push(\"PRIMVEC\");\n\n const latticeLines = formatLattice(structure.lattice);\n lines.push(...latticeLines);\n\n lines.push(\"\");\n lines.push(\"PRIMCOORD\");\n lines.push(`${structure.sites.length} 1`);\n\n for (const site of structure.sites) {\n const c = cartesian(structure.lattice, site);\n\n lines.push(`${site.species.symbol} ${c[0]} ${c[1]} ${c[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import { createLattice, Lattice } from \"../lattice/lattice\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\n\ntype ExtendedXYZInfo = Record<string, string>;\n\nfunction parseHeader(comment: string): ExtendedXYZInfo {\n const info: ExtendedXYZInfo = {};\n const kvRegex = /(\\w+)=(\".*?\"|\\S+)/g;\n\n for (const match of comment.matchAll(kvRegex)) {\n let value = match[2];\n if (value.startsWith('\"')) value = value.slice(1, -1);\n info[match[1]] = value;\n }\n\n return info;\n}\n\nfunction parseLattice(info: ExtendedXYZInfo) {\n if (!info.Lattice) {\n throw new Error(\"Extended XYZ must contain Lattice\");\n }\n\n const v = info.Lattice.split(/\\s+/).map(Number);\n if (v.length !== 9) throw new Error(\"Invalid Lattice\");\n\n return createLattice([v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]]);\n}\n\nexport function fromXYZ(text: string) {\n const lines = text.trim().split(\"\\n\");\n\n const n = Number(lines[0]);\n const comment = lines[1];\n\n const info = parseHeader(comment);\n const lattice = parseLattice(info);\n\n const sites: Site[] = [];\n\n for (let i = 0; i < n; i++) {\n const [symbol, x, y, z] = lines[2 + i].split(/\\s+/);\n\n sites.push({\n species: { symbol },\n frac: new Float64Array([+x, +y, +z]),\n });\n }\n\n return { lattice, sites };\n}\n\nfunction formatLattice(lattice: Lattice): string {\n const m = lattice.basis.data;\n\n // row-major flattening assumption (consistent with your matrix code)\n return `${m[0]} ${m[1]} ${m[2]} ${m[3]} ${m[4]} ${m[5]} ${m[6]} ${m[7]} ${m[8]}`;\n}\n\nexport function toXYZ(structure: Structure): string {\n const sites = structure.sites;\n\n const lines: string[] = [];\n\n lines.push(String(sites.length));\n\n const latticeStr = formatLattice(structure.lattice);\n\n lines.push(`Lattice=\"${latticeStr}\"`);\n\n for (const site of sites) {\n const f = site.frac;\n\n lines.push(`${site.species.symbol} ${f[0]} ${f[1]} ${f[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n"],"names":["createMatrix","rows","cols","data","size","buffer","index","row","col","EPS","clean","x","createLattice","values","cleaned","i","toJSON","structure","s","fromJSON","wrap","v","canonicalize","site","toFixedArray","precision","fnv1a","str","hash","hashStructure","lattice","latticeKey","sitesKey","key","appendSite","insertSite","removeSite","_","replaceSite","dot","a","b","sum","norm","angle","u","denom","c","clamped","angles","m","alpha","beta","gamma","inverse3x3","a00","a01","a02","a10","a11","a12","a20","a21","a22","c00","c01","c02","c10","c11","c12","c20","c21","c22","det","invDet","out","inverse","lengths","transpose","matrix","mul","aRows","aCols","bCols","k","metricTensor","AT","RAD2DEG","parameters","TWO_PI","reciprocalLattice","inv","reciprocalLatticeCrystallographic","invT","minor","skipRow","skipCol","ptr","determinant","n","sign","volume","DEG2RAD","fromParameters","alphaR","betaR","gammaR","cosA","cosB","cosG","sinG","v1","v2","cx","cy","czSquared","cz","cubic","hexagonal","monoclinic","orthorhombic","rhombohedral","tetragonal","ready","initMoyo","readFileSync","join","wasmPath","wasmBuffer","init","e","wasmUrl","getSymmetry","tolerance","setting","symbolToId","idToSymbol","counter","positions","numbers","symbol","moyoInput","results","analyze_cell","build","cell","species","sites","pos","supercell","nx","ny","nz","newBasis","y","z","j","createSite","frac","properties","cartesian","result","fractional","cart","vec","distance","dFrac","displaced","dCart","wrapValue","createSpecies","cleanValue","value","tokenize","line","warnUnsupportedSymmetry","spaceGroup","fromCIF","text","lines","atomHeaders","atomRows","inLoop","currentHeaders","collectingAtoms","ix","iy","iz","ispecies","toCIF","p","isSelective","isDirect","l","isCartesian","fromPOSCAR","cursor","scale","latticeData","symbols","counts","direct","speciesIndex","remaining","totalAtoms","coords","toPOSCAR","options","title","grouped","fromStructureData","kindMap","kind","toStructureData","kinds","findSection","section","idx","fromXSF","vecStart","coordStart","nAtoms","tokens","formatVec","formatLattice","toXSF","latticeLines","parseHeader","comment","info","kvRegex","match","parseLattice","fromXYZ","toXYZ","latticeStr","f"],"mappings":";AAMO,SAASA,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,IAAOH,IAAOC,GAEdG,IAASF,IAAO,aAAa,KAAKA,CAAI,IAAI,IAAI,aAAaC,CAAI;AAErE,MAAIC,EAAO,WAAWD;AACpB,UAAM,IAAI,MAAM,YAAYA,CAAI,gBAAgBC,EAAO,MAAM,EAAE;AAGjE,SAAO;AAAA,IACL,MAAAJ;AAAA,IACA,MAAAC;AAAA,IACA,MAAMG;AAAA,EAAA;AAEV;AAwBO,SAASC,EAAMJ,GAAcK,GAAaC,GAAqB;AACpE,SAAOD,IAAML,IAAOM;AACtB;AChDA,MAAMC,IAAM;AAEZ,SAASC,EAAMC,GAAmB;AAChC,SAAO,KAAK,IAAIA,CAAC,IAAIF,IAAM,IAAIE;AACjC;AAMO,SAASC,EAAcT,GAAkC;AAC9D,QAAMU,IAAS,UAAUV,IAAOA,EAAK,OAAOA;AAE5C,MAAIU,E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C,EAAE;AAAA,EAC7D;AAEA,SAAOzD,EAAM,KAAK;AAAA,CAAI;AACxB;"}
1
+ {"version":3,"file":"index.js","sources":["../lib/core/structure/operations/canonicalize.ts","../lib/core/structure/operations/hashStructure.ts","../lib/core/structure/operations/sites/appendSite.ts","../lib/core/structure/operations/sites/insertSite.ts","../lib/core/structure/operations/sites/removeSite.ts","../lib/core/structure/operations/sites/replaceSite.ts","../lib/core/matrix/matrix.ts","../lib/core/lattice/lattice.ts","../lib/core/matrix/operations/vector/dot.ts","../lib/core/matrix/operations/vector/norm.ts","../lib/core/lattice/angles.ts","../lib/core/matrix/operations/inverse/inverse3x3.ts","../lib/core/lattice/inverse.ts","../lib/core/lattice/lengths.ts","../lib/core/matrix/operations/transpose.ts","../lib/core/matrix/operations/mul.ts","../lib/core/lattice/metricTensor.ts","../lib/core/lattice/parameters.ts","../lib/core/lattice/reciprocalLattice.ts","../lib/core/lattice/reciprocalLatticeCrystallographic.ts","../lib/core/matrix/operations/determinant.ts","../lib/core/lattice/volume.ts","../lib/core/lattice/create/fromParameters.ts","../lib/core/lattice/create/cubic.ts","../lib/core/lattice/create/hexagonal.ts","../lib/core/lattice/create/monoclinic.ts","../lib/core/lattice/create/orthorhombic.ts","../lib/core/lattice/create/rhombohedral.ts","../lib/core/lattice/create/tetragonal.ts","../lib/core/structure/operations/symmetry/spglib.ts","../lib/core/structure/operations/supercell.ts","../lib/core/site/site.ts","../lib/core/site/cartesian.ts","../lib/core/site/fractional.ts","../lib/core/site/distance.ts","../lib/core/site/wrap.ts","../lib/core/species/species.ts","../lib/core/io/cif.ts","../lib/core/io/poscar.ts","../lib/core/io/structuredata.ts","../lib/core/io/xsf.ts","../lib/core/io/xyz.ts","../lib/core/io/optimade.ts","../lib/core/io/json.ts","../lib/core/units/converter.ts","../lib/core/units/length.ts","../lib/core/units/energy.ts","../lib/core/units/angle.ts"],"sourcesContent":["import { Structure } from \"../../structure/structure\";\n\nconst EPS = 1e-12;\n\nfunction wrap(x: number): number {\n const v = x - Math.floor(x);\n return Math.abs(v) < EPS ? 0 : v;\n}\n\nfunction clean(x: number): number {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\n/**\n * Canonicalizes a structure by wrapping fractional coordinates to [0, 1).\n *\n * Ensures all atomic site coordinates are in canonical form:\n * - Fractional coordinates are wrapped to the range [0, 1)\n * - Values near machine epsilon (< 1e-12) are cleaned to 0\n * - Lattice is unchanged\n *\n * @param structure - The structure to canonicalize\n * @returns A new structure with canonicalized site coordinates\n *\n * @remarks\n * - This operation is idempotent (applying it twice gives the same result)\n * - Used for structure comparison and normalization\n * - Preserves the physical structure (atoms in equivalent positions)\n * - Does not alter the lattice\n *\n * @example\n * ```typescript\n * const structure = {\n * lattice: cubic(4),\n * sites: [\n * { species: 'Fe', frac: [1.3, -0.2, 0.5] }\n * ]\n * };\n * const canon = canonicalize(structure);\n * // frac becomes [0.3, 0.8, 0.5]\n * ```\n */\nexport function canonicalize(structure: Structure): Structure {\n return {\n ...structure,\n sites: structure.sites.map((site) => ({\n ...site,\n frac: new Float64Array([\n wrap(clean(site.frac[0])),\n wrap(clean(site.frac[1])),\n wrap(clean(site.frac[2])),\n ]),\n })),\n };\n}\n","import { Structure } from \"../structure\";\nimport { canonicalize } from \"./canonicalize\";\nimport { Vec3 } from \"@/main\";\n\nfunction toFixedArray(v: Vec3, precision = 8): string {\n return Array.from(v)\n .map((x) => x.toFixed(precision))\n .join(\",\");\n}\n\nfunction fnv1a(str: string): number {\n let hash = 2166136261;\n\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash *= 16777619;\n }\n\n return hash >>> 0;\n}\n\n/**\n * Computes a hash of a structure for fast structure identification and comparison.\n *\n * Generates a 32-bit hash using the FNV-1a algorithm based on the canonical structure.\n * Useful for detecting duplicate structures and structure database lookups.\n *\n * @param structure - The structure to hash\n * @returns A 32-bit integer hash value\n *\n * @remarks\n * - Hash is computed from the canonicalized structure (coordinates wrapped to [0,1))\n * - Same hash does NOT guarantee identical structures (hash collisions are possible)\n * - Different structures may occasionally have the same hash (false positives)\n * - Use for quick filtering; verify with full structure comparison if needed\n * - Precision: coordinates are rounded to 8 decimal places for hash calculation\n *\n * @example\n * ```typescript\n * const struct1 = { lattice: cubic(4), sites: [...] };\n * const struct2 = { ...struct1 };\n * const hash1 = hashStructure(struct1);\n * const hash2 = hashStructure(struct2);\n * console.log(hash1 === hash2); // true (same structure)\n * ```\n */\nexport function hashStructure(structure: Structure): number {\n const s = canonicalize(structure);\n\n const lattice = s.lattice.basis.data;\n const latticeKey = toFixedArray(lattice);\n\n const sitesKey = s.sites\n .map((site) => {\n return site.species + \":\" + toFixedArray(site.frac);\n })\n .sort()\n .join(\"|\");\n\n const key = latticeKey + \"::\" + sitesKey;\n\n return fnv1a(key);\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\n/**\n * Appends a new site to a structure.\n *\n * Returns a new structure with an additional atom at the end of the sites list.\n *\n * @param structure - The original structure\n * @param site - The new site to add\n * @returns A new structure with the site appended\n *\n * @remarks\n * - The original structure is not modified\n * - Useful for building structures incrementally\n * - Does not validate site position (may be outside [0,1))\n *\n * @example\n * ```typescript\n * const struct = { lattice: cubic(4), sites: [] };\n * const newSite = { species: 'Fe', frac: [0, 0, 0] };\n * const struct2 = appendSite(struct, newSite);\n * ```\n */\nexport function appendSite(structure: Structure, site: Site): Structure {\n return {\n ...structure,\n sites: [...structure.sites, site],\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\n/**\n * Inserts a site at a specific index in the structure.\n *\n * Returns a new structure with a site inserted at the specified position,\n * shifting subsequent sites forward.\n *\n * @param structure - The original structure\n * @param index - The position to insert at (0-based)\n * @param site - The site to insert\n * @returns A new structure with the site inserted\n *\n * @remarks\n * - The original structure is not modified\n * - Index should be in range [0, sites.length] (end is valid for append)\n * - Does not validate the index bounds\n *\n * @example\n * ```typescript\n * const struct = {\n * lattice: cubic(4),\n * sites: [\n * { species: 'Fe', frac: [0, 0, 0] },\n * { species: 'Fe', frac: [0.5, 0.5, 0.5] }\n * ]\n * };\n * const newSite = { species: 'C', frac: [0.5, 0, 0] };\n * const struct2 = insertSite(struct, 1, newSite); // Inserts at position 1\n * ```\n */\nexport function insertSite(\n structure: Structure,\n index: number,\n site: Site,\n): Structure {\n return {\n ...structure,\n sites: [\n ...structure.sites.slice(0, index),\n site,\n ...structure.sites.slice(index),\n ],\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\n/**\n * Removes a site from a structure at the specified index.\n *\n * Returns a new structure with the site at the given index removed.\n *\n * @param structure - The original structure\n * @param index - The position of the site to remove (0-based)\n * @returns A new structure with the site removed\n *\n * @remarks\n * - The original structure is not modified\n * - Does not validate the index; out-of-bounds indices are silently ignored\n * - Adjacent sites are shifted to fill the gap\n *\n * @example\n * ```typescript\n * const struct = {\n * lattice: cubic(4),\n * sites: [\n * { species: 'Fe', frac: [0, 0, 0] },\n * { species: 'Fe', frac: [0.5, 0.5, 0.5] }\n * ]\n * };\n * const struct2 = removeSite(struct, 0); // Removes first site\n * // Now has only one site\n * ```\n */\nexport function removeSite(structure: Structure, index: number): Structure {\n return {\n ...structure,\n sites: structure.sites.filter((_, i) => i !== index),\n };\n}\n","import { Structure } from \"../../structure\";\nimport { Site } from \"../../../site/site\";\n\n/**\n * Replaces a site in a structure at the specified index.\n *\n * Returns a new structure with the site at the given index replaced with a new site.\n *\n * @param structure - The original structure\n * @param index - The position of the site to replace (0-based)\n * @param site - The new site to use in place of the old one\n * @returns A new structure with the site replaced\n *\n * @remarks\n * - The original structure is not modified\n * - Only the site at the exact index is affected\n * - Does not validate the index bounds\n *\n * @example\n * ```typescript\n * const struct = {\n * lattice: cubic(4),\n * sites: [\n * { species: 'Fe', frac: [0, 0, 0] },\n * { species: 'Fe', frac: [0.5, 0.5, 0.5] }\n * ]\n * };\n * const newSite = { species: 'Ni', frac: [0, 0, 0] };\n * const struct2 = replaceSite(struct, 0, newSite); // Changes first Fe to Ni\n * ```\n */\nexport function replaceSite(\n structure: Structure,\n index: number,\n site: Site,\n): Structure {\n return {\n ...structure,\n sites: structure.sites.map((s, i) => (i === index ? site : s)),\n };\n}\n","/**\n * A 2D matrix with row-major storage layout.\n *\n * Data is stored in a single `Float64Array` buffer in row-major order,\n * meaning elements are accessed as `data[row * cols + col]`.\n *\n * @remarks\n * - All matrices are immutable; operations return new matrices\n * - Use the `index()` helper function to calculate element positions\n * - Dimensions are read-only properties\n *\n * @example\n * ```typescript\n * const m = createMatrix(2, 3, [1, 2, 3, 4, 5, 6]);\n * console.log(m.rows); // 2\n * console.log(m.cols); // 3\n * ```\n */\nexport interface Matrix {\n readonly rows: number;\n readonly cols: number;\n readonly data: Float64Array;\n}\n\n/**\n * Creates a new matrix with specified dimensions.\n *\n * If data is provided, it is converted to a Float64Array and validated to ensure\n * the correct number of elements. If no data is provided, the matrix is initialized\n * with zeros.\n *\n * @param rows - Number of rows in the matrix\n * @param cols - Number of columns in the matrix\n * @param data - Optional iterable of numbers to populate the matrix (row-major order)\n * @returns A new Matrix object\n * @throws Error if the provided data length does not match rows * cols\n *\n * @example\n * ```typescript\n * const m1 = createMatrix(2, 3); // 2x3 matrix of zeros\n * const m2 = createMatrix(2, 3, [1, 2, 3, 4, 5, 6]); // 2x3 matrix with data\n * ```\n */\nexport function createMatrix(\n rows: number,\n cols: number,\n data?: Iterable<number>,\n): Matrix {\n const size = rows * cols;\n\n const buffer = data ? Float64Array.from(data) : new Float64Array(size);\n\n if (buffer.length !== size) {\n throw new Error(`Expected ${size} values, got ${buffer.length}`);\n }\n\n return {\n rows,\n cols,\n data: buffer,\n };\n}\n\n/**\n * Creates an identity matrix of the specified size.\n *\n * An identity matrix is a square matrix with ones on the main diagonal\n * and zeros elsewhere.\n *\n * @param size - The size of the identity matrix (size × size)\n * @returns An identity Matrix\n *\n * @example\n * ```typescript\n * const id = identity(3);\n * // Represents:\n * // [ 1 0 0 ]\n * // [ 0 1 0 ]\n * // [ 0 0 1 ]\n * ```\n */\nexport function identity(size: number): Matrix {\n const data = new Float64Array(size * size);\n\n for (let i = 0; i < size; i++) {\n data[i * size + i] = 1;\n }\n\n return {\n rows: size,\n cols: size,\n data,\n };\n}\n\n/**\n * Creates a deep copy of a matrix.\n *\n * The returned matrix is independent of the original; modifications to one\n * do not affect the other.\n *\n * @param matrix - The matrix to clone\n * @returns A new Matrix with the same values as the input\n *\n * @example\n * ```typescript\n * const m1 = createMatrix(2, 2, [1, 2, 3, 4]);\n * const m2 = clone(m1);\n * // m1 and m2 have the same values but are different objects\n * ```\n */\nexport function clone(matrix: Matrix): Matrix {\n return {\n rows: matrix.rows,\n cols: matrix.cols,\n data: new Float64Array(matrix.data),\n };\n}\n\n/**\n * Calculates the linear index in a row-major matrix's data array.\n *\n * Given a matrix's column count and a row/column position, returns the\n * corresponding index in the flattened data array.\n *\n * @param cols - The number of columns in the matrix\n * @param row - The row index (0-based)\n * @param col - The column index (0-based)\n * @returns The linear index in the flattened data array\n *\n * @example\n * ```typescript\n * // For a matrix with 3 columns, element at row 1, col 2 is at index:\n * const idx = index(3, 1, 2); // returns 5 (1 * 3 + 2)\n * ```\n */\nexport function index(cols: number, row: number, col: number): number {\n return row * cols + col;\n}\n","import { createMatrix, Matrix } from \"../matrix/matrix\";\n\nconst EPS = 1e-12;\n\nfunction clean(x: number): number {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\n/**\n * Represents a crystallographic lattice with a 3x3 basis matrix.\n *\n * @remarks\n * The basis matrix contains three lattice vectors as rows:\n * - Row 0: First lattice vector **a**\n * - Row 1: Second lattice vector **b**\n * - Row 2: Third lattice vector **c**\n *\n * This representation is compatible with standard crystallographic conventions.\n */\nexport interface Lattice {\n readonly basis: Matrix;\n}\n\n/**\n * Creates a Lattice from a 3x3 basis matrix.\n *\n * @param data - Either a flat array of 9 numbers or a 3x3 Matrix representing the lattice basis vectors.\n * The values should be organized as [a1, a2, a3, b1, b2, b3, c1, c2, c3]\n * where a, b, c are the three lattice vectors.\n *\n * @returns A new Lattice object with the provided basis matrix.\n *\n * @throws Will throw an error if the data does not contain exactly 9 elements.\n *\n * @remarks\n * - Very small values (< 1e-12 in magnitude) are automatically cleaned to zero\n * - The function accepts either a flat array or a Matrix object\n *\n * @example\n * ```typescript\n * // Create a cubic lattice with edge length 5 Ångströms\n * const lattice = createLattice([\n * 5, 0, 0,\n * 0, 5, 0,\n * 0, 0, 5\n * ]);\n * ```\n */\nexport function createLattice(data: number[] | Float64Array | Matrix): Lattice {\n const values =\n data instanceof Float64Array ? data : \"data\" in data ? data.data : data;\n\n if (values.length !== 9) {\n throw new Error(\"Lattice requires 9 values (3x3)\");\n }\n\n const cleaned = new Float64Array(9);\n\n for (let i = 0; i < 9; i++) {\n cleaned[i] = clean(values[i]);\n }\n\n return {\n basis: createMatrix(3, 3, cleaned),\n };\n}\n","import { Vector } from \"../../vector\";\n\n/**\n * Computes the dot product of two vectors.\n *\n * The dot product measures the similarity between two vectors and is fundamental\n * in linear algebra. It represents: a · b = Σ aᵢ × bᵢ\n *\n * @param a - The first vector\n * @param b - The second vector\n * @returns The scalar dot product\n * @throws Error if the vectors have different lengths\n *\n * @remarks\n * - Result is 0 if vectors are perpendicular\n * - Result is positive if vectors point in similar directions\n * - Result is negative if vectors point in opposite directions\n *\n * @example\n * ```typescript\n * const a = new Float64Array([1, 2, 3]) as Vector;\n * const b = new Float64Array([4, 5, 6]) as Vector;\n * const product = dot(a, b); // 32\n * ```\n */\nexport function dot(a: Vector, b: Vector): number {\n if (a.length !== b.length) {\n throw new Error(\"Dot product requires same-length vectors\");\n }\n\n let sum = 0;\n\n for (let i = 0; i < a.length; i++) {\n sum += a[i] * b[i];\n }\n\n return sum;\n}\n","import { Vector } from \"../../vector\";\n\nconst EPS = 1e-12;\n\n/**\n * Computes the Euclidean norm (L2 norm) of a vector.\n *\n * The norm represents the magnitude or length of the vector:\n * ‖v‖ = √(Σ vᵢ²)\n *\n * @param v - The vector\n * @returns The norm value (always non-negative)\n *\n * @remarks\n * - A norm of 0 indicates a zero vector\n * - Used in convergence tests, error metrics, and normalization\n * - Also known as the Euclidean distance from origin\n *\n * @example\n * ```typescript\n * const v = new Float64Array([3, 4]) as Vector;\n * const n = norm(v); // 5\n * ```\n */\nexport function norm(v: Vector): number {\n let sum = 0;\n\n for (let i = 0; i < v.length; i++) {\n const x = v[i];\n sum += x * x;\n }\n\n return Math.sqrt(sum);\n}\n","import { dot } from \"../matrix/operations/vector/dot\";\nimport { norm } from \"../matrix/operations/vector/norm\";\nimport { Lattice } from \"./lattice\";\n\nimport { Vector } from \"../matrix/vector\";\n\nfunction angle(u: Vector, v: Vector) {\n const denom = norm(u) * norm(v);\n if (denom === 0) throw new Error(\"Zero-length lattice vector\");\n\n const c = dot(u, v) / denom;\n const clamped = Math.max(-1, Math.min(1, c));\n\n return Math.acos(clamped);\n}\n\n/**\n * Computes the three angles of a lattice in radians.\n *\n * @param lattice - The lattice to compute angles for.\n *\n * @returns A tuple [alpha, beta, gamma] containing the three lattice angles in **radians**.\n * - **alpha**: Angle between lattice vectors **b** and **c**\n * - **beta**: Angle between lattice vectors **a** and **c**\n * - **gamma**: Angle between lattice vectors **a** and **b**\n *\n * @throws Will throw an error if any lattice vector has zero length.\n *\n * @remarks\n * - All angles are returned in **radians**, not degrees\n * - To convert to degrees, multiply by 180/π\n * - Uses the dot product formula: cos(θ) = (u·v) / (|u| × |v|)\n * - Results are clamped to the valid range [-1, 1] before applying arccos to avoid numerical errors\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const [alpha, beta, gamma] = angles(lattice);\n * // For cubic: alpha ≈ 1.5708 rad (90°), beta ≈ 1.5708 rad, gamma ≈ 1.5708 rad\n * console.log(alpha * 180 / Math.PI); // 90 degrees\n * ```\n */\n/**\n * Computes the angles between lattice vectors in a crystal lattice.\n *\n * Returns the three angles in crystallography notation:\n * - α (alpha): angle between lattice vectors b and c\n * - β (beta): angle between lattice vectors a and c\n * - γ (gamma): angle between lattice vectors a and b\n *\n * @param lattice - The crystal lattice\n * @returns A tuple [α, β, γ] with angles in radians\n * @throws Error if any lattice vector has zero length\n *\n * @remarks\n * - Angles are returned in radians (use RAD2DEG conversion for degrees)\n * - All angles are in range [0, π]\n * - Used with edge lengths to fully specify crystal geometry\n * - For typical crystal systems: cubic/ortho have 90°, others vary\n *\n * @example\n * ```typescript\n * const lattice = cubic(4);\n * const [alpha, beta, gamma] = angles(lattice);\n * console.log(alpha * 180/Math.PI); // ~90 degrees\n * ```\n */\nexport function angles(lattice: Lattice): [number, number, number] {\n const m = lattice.basis.data;\n\n const a: Vector = new Float64Array([m[0], m[1], m[2]]);\n const b: Vector = new Float64Array([m[3], m[4], m[5]]);\n const c: Vector = new Float64Array([m[6], m[7], m[8]]);\n\n const alpha = angle(b, c);\n const beta = angle(a, c);\n const gamma = angle(a, b);\n\n return [alpha, beta, gamma];\n}\n","import { Matrix, createMatrix } from \"../../matrix\";\n\n/**\n * Computes the inverse of a 3×3 matrix.\n *\n * Uses the analytical formula based on matrix of minors/cofactors.\n * This is faster than general LU-based methods for small matrices.\n *\n * @param m - The 3×3 matrix to invert\n * @returns The inverted matrix\n * @throws Error if the matrix is not 3×3\n * @throws Error if the matrix is singular (determinant is 0)\n *\n * @remarks\n * The 3×3 inverse is computed using the cofactor method:\n * A⁻¹ = (1/det(A)) * adj(A), where adj(A) is the adjugate matrix.\n *\n * @example\n * ```typescript\n * const m = createMatrix(3, 3, [1, 0, 0, 0, 1, 0, 0, 0, 1]);\n * const inv = inverse3x3(m); // Identity matrix (already invertible)\n * ```\n */\nexport function inverse3x3(m: Matrix): Matrix {\n if (m.rows !== 3 || m.cols !== 3) {\n throw new Error(\"Expected 3x3 matrix\");\n }\n\n const a00 = m.data[0],\n a01 = m.data[1],\n a02 = m.data[2];\n const a10 = m.data[3],\n a11 = m.data[4],\n a12 = m.data[5];\n const a20 = m.data[6],\n a21 = m.data[7],\n a22 = m.data[8];\n\n const c00 = a11 * a22 - a12 * a21;\n const c01 = a12 * a20 - a10 * a22;\n const c02 = a10 * a21 - a11 * a20;\n\n const c10 = a02 * a21 - a01 * a22;\n const c11 = a00 * a22 - a02 * a20;\n const c12 = a01 * a20 - a00 * a21;\n\n const c20 = a01 * a12 - a02 * a11;\n const c21 = a02 * a10 - a00 * a12;\n const c22 = a00 * a11 - a01 * a10;\n\n const det = a00 * c00 + a01 * c01 + a02 * c02;\n\n if (det === 0) {\n throw new Error(\"Singular matrix\");\n }\n\n const invDet = 1 / det;\n\n const out = createMatrix(3, 3);\n\n out.data[0] = c00 * invDet;\n out.data[1] = c10 * invDet;\n out.data[2] = c20 * invDet;\n\n out.data[3] = c01 * invDet;\n out.data[4] = c11 * invDet;\n out.data[5] = c21 * invDet;\n\n out.data[6] = c02 * invDet;\n out.data[7] = c12 * invDet;\n out.data[8] = c22 * invDet;\n\n return out;\n}\n","import { Lattice } from \"./lattice\";\nimport { inverse3x3 } from \"../matrix/operations/inverse/inverse3x3\";\nimport { Matrix } from \"../matrix/matrix\";\n\n/**\n * Computes the inverse of a lattice basis matrix.\n *\n * @param lattice - The lattice for which to compute the inverse.\n *\n * @returns A 3x3 Matrix representing the inverse of the lattice basis matrix (A^{-1}).\n *\n * @remarks\n * The inverse lattice basis is used to:\n * - Construct the reciprocal lattice (when combined with a 2π scaling)\n * - Convert between real space and reciprocal space coordinates\n * - Compute crystallographic quantities like d-spacings and scattering angles\n *\n * The relationship is: A^{-1} × A = I (identity matrix)\n *\n * @throws Will throw an error if the lattice basis matrix is singular (determinant = 0).\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const inv = inverse(lattice);\n * // For this cubic lattice: inv = [[0.2, 0, 0], [0, 0.2, 0], [0, 0, 0.2]]\n * ```\n */\n/**\n * Computes the inverse of the lattice basis matrix.\n *\n * The inverse matrix maps from Cartesian coordinates to fractional (crystal) coordinates.\n * This is fundamental for coordinate transformations in crystallography.\n *\n * @param lattice - The crystal lattice\n * @returns The inverse of the basis matrix (3×3)\n * @throws Error if the lattice basis is singular\n *\n * @remarks\n * - If B = A⁻¹ (inverse), then B × r_cartesian = r_fractional\n * - Used for converting Cartesian to fractional coordinates\n * - Uses analytical 3×3 matrix inversion for speed and stability\n * - Related to reciprocal lattice calculations\n *\n * @example\n * ```typescript\n * const lattice = cubic(4);\n * const inv = inverse(lattice);\n * // inv × [4, 0, 0] = [1, 0, 0] in fractional coordinates\n * ```\n */\nexport function inverse(lattice: Lattice): Matrix {\n return inverse3x3(lattice.basis);\n}\n","import { norm } from \"../matrix/operations/vector/norm\";\nimport { Lattice } from \"./lattice\";\n\n/**\n * Computes the lengths (magnitudes) of the three lattice vectors.\n *\n * @param lattice - The lattice to compute edge lengths for.\n *\n * @returns A tuple [a, b, c] containing the lengths of the three lattice vectors.\n * - **a**: Length of the first lattice vector\n * - **b**: Length of the second lattice vector\n * - **c**: Length of the third lattice vector\n *\n * @remarks\n * In crystallographic notation, these lengths are typically denoted as |**a**|, |**b**|, and |**c**|,\n * and are usually measured in Ångströms (Å) or picometers (pm).\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 6, 0, 0, 0, 7]);\n * const [a, b, c] = lengths(lattice);\n * // a = 5, b = 6, c = 7\n * ```\n */\n/**\n * Computes the lengths (magnitudes) of lattice vectors.\n *\n * Returns the three edge lengths in crystallography notation: a, b, c.\n * These represent the magnitudes of the three basis vectors.\n *\n * @param lattice - The crystal lattice\n * @returns A tuple [a, b, c] with the edge lengths\n *\n * @remarks\n * - Lengths are always positive\n * - Used with angles to fully specify lattice geometry\n * - Combined with angles(), provides the lattice parameters\n * - For cubic systems: a = b = c\n *\n * @example\n * ```typescript\n * const lattice = cubic(4.5);\n * const [a, b, c] = lengths(lattice);\n * console.log(a); // 4.5\n * ```\n */\nexport function lengths(lattice: Lattice): [number, number, number] {\n const m = lattice.basis.data;\n\n const a: Float64Array = new Float64Array([m[0], m[1], m[2]]);\n const b: Float64Array = new Float64Array([m[3], m[4], m[5]]);\n const c: Float64Array = new Float64Array([m[6], m[7], m[8]]);\n\n return [norm(a), norm(b), norm(c)];\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\n/**\n * Transposes a matrix by swapping rows and columns.\n *\n * Returns a new matrix where element (i, j) becomes element (j, i).\n * A matrix of size (m × n) becomes (n × m).\n *\n * @param matrix - The matrix to transpose\n * @returns A new transposed matrix\n *\n * @example\n * ```typescript\n * const m = createMatrix(2, 3, [1, 2, 3, 4, 5, 6]);\n * // Represents: [[1, 2, 3], [4, 5, 6]]\n * const t = transpose(m);\n * // Represents: [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nexport function transpose(matrix: Matrix): Matrix {\n const out = createMatrix(matrix.cols, matrix.rows);\n\n for (let row = 0; row < matrix.rows; row++) {\n for (let col = 0; col < matrix.cols; col++) {\n out.data[index(out.cols, col, row)] =\n matrix.data[index(matrix.cols, row, col)];\n }\n }\n\n return out;\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\n/**\n * Multiplies two matrices.\n *\n * Performs standard matrix multiplication: C = A × B. The number of columns in A\n * must equal the number of rows in B. The result has dimensions (A.rows × B.cols).\n *\n * @param a - The first matrix (left operand)\n * @param b - The second matrix (right operand)\n * @returns A new matrix containing the product\n * @throws Error if matrix dimensions are incompatible for multiplication\n *\n * @remarks\n * Matrix multiplication is not commutative; A × B ≠ B × A in general.\n *\n * @example\n * ```typescript\n * const a = createMatrix(2, 3, [1, 2, 3, 4, 5, 6]);\n * const b = createMatrix(3, 2, [7, 8, 9, 10, 11, 12]);\n * const result = mul(a, b); // 2x2 matrix\n * ```\n */\nexport function mul(a: Matrix, b: Matrix): Matrix {\n if (a.cols !== b.rows) {\n throw new Error(\"Invalid matrix multiplication dimensions\");\n }\n\n const out = createMatrix(a.rows, b.cols);\n\n const aRows = a.rows;\n const aCols = a.cols;\n const bCols = b.cols;\n\n for (let row = 0; row < aRows; row++) {\n for (let col = 0; col < bCols; col++) {\n let sum = 0;\n\n for (let k = 0; k < aCols; k++) {\n sum += a.data[index(a.cols, row, k)] * b.data[index(b.cols, k, col)];\n }\n\n out.data[index(out.cols, row, col)] = sum;\n }\n }\n\n return out;\n}\n","import { transpose } from \"../matrix/operations/transpose\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { Lattice } from \"./lattice\";\nimport { Matrix } from \"../matrix/matrix\";\n\n/**\n * Computes the metric tensor of a lattice.\n *\n * @param lattice - The lattice for which to compute the metric tensor.\n *\n * @returns A 3x3 Matrix representing the metric tensor G = A^T × A,\n * where A is the lattice basis matrix.\n *\n * @remarks\n * The metric tensor is a fundamental quantity in crystallography that encodes all\n * geometric information about the lattice:\n * - Diagonal elements: G_ii = |v_i|² (squared lengths of lattice vectors)\n * - Off-diagonal elements: G_ij = v_i · v_j (dot products of vector pairs)\n * - The determinant of G equals the square of the lattice volume: det(G) = V²\n * - The metric tensor is symmetric: G_ij = G_ji\n *\n * The metric tensor is widely used in:\n * - Calculating distances between atoms\n * - Computing reciprocal lattice properties\n * - Crystallographic computations (Miller indices, d-spacings)\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const G = metricTensor(lattice);\n * // For cubic: G = [[25, 0, 0], [0, 25, 0], [0, 0, 25]]\n * console.log(G.data); // [25, 0, 0, 0, 25, 0, 0, 0, 25]\n * ```\n */\n/**\n * Computes the metric tensor of a lattice.\n *\n * The metric tensor G is defined as G = A^T × A, where A is the basis matrix.\n * It encodes all geometric information about the lattice (distances, angles, volume).\n *\n * @param lattice - The crystal lattice\n * @returns The 3×3 metric tensor matrix\n *\n * @remarks\n * - The metric tensor is always symmetric and positive-definite\n * - Diagonal elements: G[i,i] = |v_i|² (squared edge lengths)\n * - Off-diagonal: G[i,j] = v_i · v_j = |v_i||v_j|cos(angle)\n * - Used in reciprocal space calculations and structure analysis\n * - Inverse of metric tensor gives reciprocal metric tensor\n *\n * @example\n * ```typescript\n * const lattice = cubic(4);\n * const G = metricTensor(lattice);\n * // For cubic: G[0,0] = G[1,1] = G[2,2] = 16 (4²)\n * // Off-diagonal elements = 0\n * ```\n */\nexport function metricTensor(lattice: Lattice): Matrix {\n const A = lattice.basis;\n\n const AT = transpose(A);\n return mul(AT, A);\n}\n","import { lengths } from \"./lengths\";\nimport { angles } from \"./angles\";\nimport { Lattice } from \"./lattice\";\n\nconst RAD2DEG = 180 / Math.PI;\n\n/**\n * Extracts the standard crystallographic parameters from a lattice.\n *\n * @param lattice - The lattice to extract parameters from.\n *\n * @returns A tuple [a, b, c, alpha, beta, gamma] containing:\n * - **a, b, c**: Edge lengths of the unit cell\n * - **alpha, beta, gamma**: Angles of the unit cell in **degrees**\n *\n * @remarks\n * - Edge lengths are in the same units as the lattice basis vectors\n * - **Angles are returned in degrees (not radians)**\n * - alpha is the angle between **b** and **c**\n * - beta is the angle between **a** and **c**\n * - gamma is the angle between **a** and **b**\n * - Conversion formula: degrees = radians × (180/π)\n *\n * @example\n * ```typescript\n * // Cubic system\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const [a, b, c, alpha, beta, gamma] = parameters(lattice);\n * // [5, 5, 5, 90, 90, 90]\n *\n * // Hexagonal system\n * const hex = hexagonal(3.0, 5.0);\n * const [a2, b2, c2, alpha2, beta2, gamma2] = parameters(hex);\n * // [3.0, 3.0, 5.0, 90, 90, 120]\n * ```\n */\n/**\n * Computes all six lattice parameters from a lattice basis.\n *\n * Returns the complete lattice specification in standard crystallographic notation:\n * [a, b, c, α, β, γ] where a, b, c are edge lengths and α, β, γ are angles.\n *\n * @param lattice - The crystal lattice\n * @returns A tuple [a, b, c, alpha, beta, gamma] where angles are in degrees\n *\n * @remarks\n * - Angles are converted from radians to degrees (multiplied by 180/π)\n * - This is the standard representation used in crystallography\n * - Combines results from lengths() and angles() functions\n * - Used for crystal database storage and structure file formats (CIF, etc.)\n *\n * @example\n * ```typescript\n * const lattice = cubic(4.05);\n * const params = parameters(lattice);\n * // [4.05, 4.05, 4.05, 90, 90, 90]\n * ```\n */\nexport function parameters(\n lattice: Lattice,\n): [number, number, number, number, number, number] {\n const [a, b, c] = lengths(lattice);\n const [alpha, beta, gamma] = angles(lattice);\n\n return [a, b, c, alpha * RAD2DEG, beta * RAD2DEG, gamma * RAD2DEG];\n}\n","import { Lattice } from \"./lattice\";\nimport { inverse } from \"./inverse\";\nimport { transpose } from \"../matrix/operations/transpose\";\nimport { createMatrix } from \"../matrix/matrix\";\nimport { createLattice } from \"./lattice\";\n\nconst TWO_PI = 2 * Math.PI;\n\n/**\n * Computes the reciprocal lattice with 2π scaling (physics convention).\n *\n * @param lattice - The real-space lattice for which to compute the reciprocal lattice.\n *\n * @returns A new Lattice object representing the reciprocal lattice with 2π scaling.\n *\n * @remarks\n * The reciprocal lattice is fundamental in crystallography and solid-state physics:\n * - **Physics convention**: Uses 2π scaling (this function)\n * - **Crystallographic convention**: No 2π scaling (see {@link reciprocalLatticeCrystallographic})\n *\n * Formula: b_i = 2π × (a_j × a_k) / V, where i, j, k are cyclic indices and V is the cell volume\n *\n * The reciprocal lattice vectors are perpendicular to planes in the real lattice:\n * - **b** is perpendicular to the plane defined by **a** and **c**\n * - **c** is perpendicular to the plane defined by **a** and **b**\n * - **a** is perpendicular to the plane defined by **b** and **c**\n *\n * Applications:\n * - X-ray and neutron diffraction calculations\n * - Brillouin zone construction\n * - Phonon and electronic band structure\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const recip = reciprocalLattice(lattice);\n * // For cubic with a=5: reciprocal vectors have length 2π/5\n * ```\n */\n/**\n * Computes the reciprocal lattice with 2π scaling (physics convention).\n *\n * The reciprocal lattice is the Fourier transform of the real lattice.\n * Reciprocal vectors b_i* satisfy: b_i* · a_j = 2π δ_ij (Kronecker delta).\n *\n * @param lattice - The real-space crystal lattice\n * @returns A new Lattice object representing the reciprocal lattice\n *\n * @remarks\n * - Uses physics convention with 2π scaling (common in solid-state physics)\n * - Reciprocal lattice vectors are obtained from (A⁻¹)^T × 2π\n * - Reciprocal of reciprocal ≈ original (up to 2π factors)\n * - Used in diffraction calculations (X-ray, neutron, electron)\n * - For crystallography convention without 2π, use reciprocalLatticeCrystallographic()\n *\n * @example\n * ```typescript\n * const real = cubic(4);\n * const recip = reciprocalLattice(real);\n * const recipParams = parameters(recip);\n * // For cubic: reciprocal is also cubic with a* = 2π/a\n * ```\n */\nexport function reciprocalLattice(lattice: Lattice): Lattice {\n const inv = inverse(lattice);\n const invT = transpose(inv);\n\n const data = invT.data.map((v) => v * TWO_PI);\n\n return createLattice(data);\n}\n","import { Lattice, createLattice } from \"./lattice\";\nimport { inverse } from \"./inverse\";\nimport { transpose } from \"../matrix/operations/transpose\";\n\n/**\n * Computes the reciprocal lattice without 2π scaling (crystallographic convention).\n *\n * @param lattice - The real-space lattice for which to compute the reciprocal lattice.\n *\n * @returns A new Lattice object representing the reciprocal lattice without 2π scaling.\n *\n * @remarks\n * The reciprocal lattice in crystallographic convention (no 2π):\n * - **Crystallographic convention**: No 2π scaling (this function)\n * - **Physics convention**: Uses 2π scaling (see {@link reciprocalLattice})\n *\n * Formula: b_i = (a_j × a_k) / V, where i, j, k are cyclic indices and V is the cell volume\n *\n * This convention is standard in crystallography (IUCr) where reciprocal lattice vectors\n * are directly used for indexing planes via Miller indices (h, k, l).\n *\n * Relationship with physics convention: b_cryst = b_physics / (2π)\n *\n * Applications in crystallography:\n * - Miller index calculations\n * - d-spacing determinations\n * - Structure factor computations\n * - Bragg's law calculations\n *\n * @example\n * ```typescript\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const recipCryst = reciprocalLatticeCrystallographic(lattice);\n * // For cubic with a=5: reciprocal vectors have length 1/5\n * ```\n */\n/**\n * Computes the reciprocal lattice without 2π scaling (crystallography convention).\n *\n * Similar to reciprocalLattice() but uses crystallography convention where\n * reciprocal vectors b_i* satisfy: b_i* · a_j = δ_ij (without 2π).\n *\n * @param lattice - The real-space crystal lattice\n * @returns A new Lattice object representing the reciprocal lattice\n *\n * @remarks\n * - Uses crystallography convention (no 2π scaling)\n * - Reciprocal lattice vectors are (A⁻¹)^T\n * - Used in crystallographic software and databases\n * - For physics convention with 2π, use reciprocalLattice()\n * - Related to structure factor calculations and diffraction\n *\n * @example\n * ```typescript\n * const real = cubic(4);\n * const recip = reciprocalLatticeCrystallographic(real);\n * const recipParams = parameters(recip);\n * // For cubic: reciprocal is also cubic with a* = 1/a\n * ```\n */\nexport function reciprocalLatticeCrystallographic(lattice: Lattice): Lattice {\n const inv = inverse(lattice);\n const invT = transpose(inv);\n\n return createLattice(invT.data);\n}\n","import { Matrix, createMatrix, index } from \"../matrix\";\n\nfunction minor(matrix: Matrix, skipRow: number, skipCol: number): Matrix {\n const out = createMatrix(matrix.rows - 1, matrix.cols - 1);\n\n let ptr = 0;\n\n for (let row = 0; row < matrix.rows; row++) {\n if (row === skipRow) continue;\n\n for (let col = 0; col < matrix.cols; col++) {\n if (col === skipCol) continue;\n\n out.data[ptr++] = matrix.data[index(matrix.cols, row, col)];\n }\n }\n\n return out;\n}\n\n/**\n * Computes the determinant of a matrix.\n *\n * The determinant is a scalar value that provides information about the matrix\n * (invertibility, volume scaling, orientation). Only defined for square matrices.\n *\n * @param matrix - The square matrix\n * @returns The determinant value\n * @throws Error if the matrix is not square\n *\n * @remarks\n * - A determinant of 0 indicates the matrix is singular (not invertible)\n * - Uses recursive cofactor expansion\n * - Computationally expensive for large matrices (O(n!) complexity)\n * - For performance-critical applications, consider using the rank or LU decomposition instead\n *\n * @example\n * ```typescript\n * const m = createMatrix(2, 2, [1, 2, 3, 4]);\n * const det = determinant(m); // -2\n * ```\n */\nexport function determinant(matrix: Matrix): number {\n if (matrix.rows !== matrix.cols) {\n throw new Error(\"Determinant requires a square matrix\");\n }\n\n const n = matrix.rows;\n\n // fast path for BZ / geometry\n if (n === 3) {\n const m = matrix.data;\n\n return (\n m[0] * (m[4] * m[8] - m[5] * m[7]) -\n m[1] * (m[3] * m[8] - m[5] * m[6]) +\n m[2] * (m[3] * m[7] - m[4] * m[6])\n );\n }\n\n if (n === 1) {\n return matrix.data[0];\n }\n\n if (n === 2) {\n return matrix.data[0] * matrix.data[3] - matrix.data[1] * matrix.data[2];\n }\n\n let det = 0;\n\n for (let col = 0; col < n; col++) {\n const sign = col % 2 === 0 ? 1 : -1;\n\n det += sign * matrix.data[col] * determinant(minor(matrix, 0, col));\n }\n\n return det;\n}\n","import { determinant } from \"../matrix/operations/determinant\";\nimport { Lattice } from \"./lattice\";\n\n/**\n * Computes the volume of a unit cell defined by a lattice.\n *\n * @param lattice - The lattice for which to compute the volume.\n *\n * @returns The volume of the unit cell, calculated as the absolute value of the\n * determinant of the lattice basis matrix: |det(A)|.\n *\n * @remarks\n * The volume is always positive, regardless of the lattice basis orientation.\n * The formula used is: V = |**a** · (**b** × **c**)|, where **a**, **b**, **c** are the lattice vectors.\n * This is also known as the scalar triple product.\n *\n * @example\n * ```typescript\n * // Cubic lattice with edge length 5 Ångströms\n * const lattice = createLattice([5, 0, 0, 0, 5, 0, 0, 0, 5]);\n * const vol = volume(lattice);\n * // vol = 125 (Ångströms)³\n * ```\n */\n/**\n * Computes the volume of the unit cell defined by the lattice.\n *\n * The volume is the absolute value of the determinant of the basis matrix.\n * It represents the volume of the parallelepiped formed by the three basis vectors.\n *\n * @param lattice - The crystal lattice\n * @returns The unit cell volume\n *\n * @remarks\n * - Volume is always non-negative\n * - For cubic: V = a³\n * - For orthorhombic: V = a × b × c\n * - General case: V = |det(basis)|\n * - Used in density calculations and structure normalization\n *\n * @example\n * ```typescript\n * const lattice = cubic(4);\n * const vol = volume(lattice); // 64\n * ```\n */\nexport function volume(lattice: Lattice): number {\n return Math.abs(determinant(lattice.basis));\n}\n","import { createLattice } from \"../lattice\";\n\nconst DEG2RAD = Math.PI / 180;\nconst EPS = 1e-12;\n\nfunction clean(x: number) {\n return Math.abs(x) < EPS ? 0 : x;\n}\n\n/**\n * Creates a lattice from crystallographic parameters.\n *\n * @param a - First edge length (in the same units as the output, typically Ångströms)\n * @param b - Second edge length\n * @param c - Third edge length\n * @param alpha - Angle between lattice vectors **b** and **c** in **degrees**\n * @param beta - Angle between lattice vectors **a** and **c** in **degrees**\n * @param gamma - Angle between lattice vectors **a** and **b** in **degrees**\n *\n * @returns A new Lattice object with the specified parameters.\n *\n * @throws Will throw an error if gamma is too close to 0° or 180° (degenerate configuration)\n *\n * @remarks\n * This is the primary builder for lattices from crystallographic parameters.\n * It constructs a 3x3 lattice basis matrix from edge lengths and angles using the\n * following algorithm:\n * - **v1** = (a, 0, 0)\n * - **v2** = (b cos γ, b sin γ, 0)\n * - **v3** = (c cos β, (c(cos α - cos β cos γ))/sin γ, c√(1 - cos²β - sin²(γ)...))\n *\n * **Input Constraints:**\n * - All edge lengths must be positive\n * - All angles must be in the range (0°, 180°)\n * - Gamma angle must not be too close to 0° or 180° to avoid singularity\n * - Very small values (< 1e-12) are automatically cleaned to zero\n *\n * The parameters are in the standard crystallographic convention, commonly used in:\n * - Crystal structure determination\n * - Crystallographic data files (CIF, PDB)\n * - Materials databases\n *\n * @example\n * ```typescript\n * // Create an orthorhombic lattice\n * const ortho = fromParameters(3.5, 4.0, 6.5, 90, 90, 90);\n *\n * // Create a hexagonal lattice\n * const hex = fromParameters(3.2, 3.2, 5.2, 90, 90, 120);\n *\n * // Create a monoclinic lattice\n * const mono = fromParameters(5, 6, 7, 90, 100, 90);\n * ```\n */\n/**\n * Creates a lattice from crystallographic lattice parameters.\n *\n * Constructs a lattice basis matrix from the six lattice parameters: three edge lengths\n * (a, b, c) and three angles (α, β, γ). This is the standard method for specifying\n * crystal structures.\n *\n * @param a - First edge length\n * @param b - Second edge length\n * @param c - Third edge length\n * @param alpha - Angle between b and c vectors (in degrees)\n * @param beta - Angle between a and c vectors (in degrees)\n * @param gamma - Angle between a and b vectors (in degrees)\n * @returns A new Lattice with the specified parameters\n * @throws Error if gamma is too close to 0° or 180° (would create a degenerate lattice)\n *\n * @remarks\n * - All angles should be in degrees (converted to radians internally)\n * - Uses classical crystallographic conventions\n * - First vector: a along x-axis\n * - Second vector: b in the xy-plane\n * - Third vector: c positioned to satisfy angle constraints\n * - Underlying method for all crystal system builders (cubic, hex, etc.)\n * - Very small computed values (< 1e-12) are automatically cleaned to 0\n *\n * @example\n * ```typescript\n * // Create cubic lattice\n * const cubic = fromParameters(4, 4, 4, 90, 90, 90);\n *\n * // Create tetragonal lattice\n * const tetra = fromParameters(3, 3, 5, 90, 90, 90);\n *\n * // Create triclinic lattice\n * const tri = fromParameters(3, 4, 5, 80, 85, 95);\n * ```\n */\nexport function fromParameters(\n a: number,\n b: number,\n c: number,\n alpha: number,\n beta: number,\n gamma: number,\n) {\n const alphaR = alpha * DEG2RAD;\n const betaR = beta * DEG2RAD;\n const gammaR = gamma * DEG2RAD;\n\n const cosA = Math.cos(alphaR);\n const cosB = Math.cos(betaR);\n const cosG = Math.cos(gammaR);\n const sinG = Math.sin(gammaR);\n\n // lattice vectors\n const v1 = [a, 0, 0];\n\n const v2 = [b * cosG, b * sinG, 0];\n\n // guard against degenerate gamma\n if (Math.abs(sinG) < EPS) {\n throw new Error(\"Invalid lattice: gamma too close to 0 or 180 degrees\");\n }\n\n const cx = c * cosB;\n\n const cy = (c * (cosA - cosB * cosG)) / sinG;\n\n const czSquared = c * c - cx * cx - cy * cy;\n\n const cz = Math.sqrt(Math.max(0, czSquared));\n\n return createLattice([\n clean(v1[0]),\n clean(v1[1]),\n clean(v1[2]),\n clean(v2[0]),\n clean(v2[1]),\n clean(v2[2]),\n clean(cx),\n clean(cy),\n clean(cz),\n ]);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates a cubic lattice.\n *\n * @param a - Edge length of the cubic unit cell\n *\n * @returns A new Lattice object representing a cubic crystal system (a = b = c, α = β = γ = 90°)\n *\n * @remarks\n * The cubic crystal system is the simplest crystal system with:\n * - All three edge lengths equal (a = b = c)\n * - All three angles equal to 90° (α = β = γ = 90°)\n * - The highest symmetry (cubic symmetry group)\n *\n * Common examples of cubic crystals:\n * - Iron (Fe) - body-centered cubic (BCC)\n * - Copper (Cu), Aluminum (Al), Lead (Pb) - face-centered cubic (FCC)\n * - Diamond (C) - face-centered cubic\n * - Sodium chloride (NaCl) - rock salt structure\n * - Cesium chloride (CsCl) - simple cubic structure\n *\n * @example\n * ```typescript\n * // Create a cubic lattice with edge length 5 Ångströms\n * const lattice = cubic(5);\n * const params = parameters(lattice);\n * // params = [5, 5, 5, 90, 90, 90]\n * ```\n */\n/**\n * Creates a cubic lattice.\n *\n * A cubic lattice is the simplest crystal system with all edge lengths equal\n * and all angles equal to 90°. Commonly found in materials like iron (Fe), copper (Cu),\n * and many ionic compounds.\n *\n * @param a - The edge length of the cubic unit cell\n * @returns A cubic Lattice with lattice parameter a\n *\n * @remarks\n * - Cubic: a = b = c, α = β = γ = 90°\n * - Highest symmetry cubic crystal system\n * - Volume = a³\n * - Used by many common metals and semiconductors\n *\n * @example\n * ```typescript\n * // Aluminum lattice (a ≈ 4.05 Å)\n * const al = cubic(4.05);\n *\n * // Iron (BCC, conventional cell a ≈ 2.87 Å)\n * const fe = cubic(2.87);\n * ```\n */\nexport function cubic(a: number) {\n return fromParameters(a, a, a, 90, 90, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates a hexagonal lattice.\n *\n * @param a - In-plane edge length (first two lattice vectors, a = b)\n * @param c - Out-of-plane edge length (third lattice vector)\n *\n * @returns A new Lattice object representing a hexagonal crystal system\n * (a = b ≠ c, α = β = 90°, γ = 120°)\n *\n * @remarks\n * The hexagonal crystal system has:\n * - Two equal edge lengths in the basal plane (a = b)\n * - Third edge length generally different (c ≠ a)\n * - Basal plane angles of 90° (α = β = 90°)\n * - Angle between basal vectors of 120° (γ = 120°)\n * - High symmetry (hexagonal symmetry group)\n *\n * The 120° angle is characteristic of hexagonal close-packed arrangements,\n * where atoms form a triangular lattice in the basal plane.\n *\n * Common examples of hexagonal crystals:\n * - Magnesium (Mg) - hexagonal close-packed (HCP)\n * - Zinc (Zn) - hexagonal close-packed\n * - Graphite (C) - layered hexagonal structure\n * - Wurtzite (ZnS) - hexagonal zincblende structure\n * - SiC (silicon carbide) - hexagonal polymorph\n *\n * @example\n * ```typescript\n * // Create a hexagonal lattice like magnesium\n * // Mg: a ≈ 3.21 Å, c ≈ 5.21 Å\n * const lattice = hexagonal(3.21, 5.21);\n * const params = parameters(lattice);\n * // params ≈ [3.21, 3.21, 5.21, 90, 90, 120]\n * ```\n */\n/**\n * Creates a hexagonal lattice.\n *\n * A hexagonal lattice has two equal in-plane edge lengths with a 120° angle,\n * and a different vertical edge length. Common in materials like graphite,\n * zinc, and magnesium.\n *\n * @param a - The in-plane lattice parameter (a = b)\n * @param c - The vertical lattice parameter\n * @returns A hexagonal Lattice\n *\n * @remarks\n * - Hexagonal: a = b ≠ c, α = β = 90°, γ = 120°\n * - High symmetry in the ab-plane\n * - Used for layer materials and metal hexagonal close-packed (HCP) structures\n * - Related to rhombohedral through basis transformation\n *\n * @example\n * ```typescript\n * // Graphite (a ≈ 2.42 Å, c ≈ 6.70 Å)\n * const graphite = hexagonal(2.42, 6.70);\n *\n * // Zinc (a ≈ 2.66 Å, c ≈ 4.95 Å)\n * const zn = hexagonal(2.66, 4.95);\n * ```\n */\nexport function hexagonal(a: number, c: number) {\n return fromParameters(a, a, c, 90, 90, 120);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates a monoclinic lattice.\n *\n * @param a - First edge length\n * @param b - Second edge length\n * @param c - Third edge length\n * @param beta - Angle between lattice vectors **a** and **c** in **degrees**\n * (the only non-90° angle in the monoclinic system)\n *\n * @returns A new Lattice object representing a monoclinic crystal system\n * (a ≠ b ≠ c, α = γ = 90°, β ≠ 90°)\n *\n * @remarks\n * The monoclinic crystal system has:\n * - Three generally different edge lengths (a ≠ b ≠ c)\n * - Two angles equal to 90° (α = γ = 90°)\n * - One angle different from 90° (β ≠ 90°, typically 90° < β < 180°)\n * - One unique axis (b-axis) perpendicular to the a-c plane\n * - Monoclinic point group symmetry\n *\n * The monoclinic system is less symmetric than orthorhombic, but more symmetric than triclinic.\n * It's quite common in nature, especially for organic compounds and minerals.\n *\n * Common examples of monoclinic crystals:\n * - Gypsum (CaSO₄·2H₂O) - common mineral\n * - Azurite [Cu₃(CO₃)₂(OH)₂] - blue mineral\n * - Malachite [Cu₂(CO₃)(OH)₂] - green mineral\n * - Many pharmaceutical compounds\n * - β-sulfur (one polymorph of sulfur)\n * - Diopside (pyroxene mineral)\n *\n * @example\n * ```typescript\n * // Create a monoclinic lattice\n * // Example parameters: a = 5 Å, b = 6 Å, c = 7 Å, β = 100°\n * const lattice = monoclinic(5, 6, 7, 100);\n * const params = parameters(lattice);\n * // params ≈ [5, 6, 7, 90, 100, 90]\n * ```\n */\nexport function monoclinic(a: number, b: number, c: number, beta: number) {\n return fromParameters(a, b, c, 90, beta, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates an orthorhombic lattice.\n *\n * @param a - First edge length\n * @param b - Second edge length\n * @param c - Third edge length\n *\n * @returns A new Lattice object representing an orthorhombic crystal system\n * (a ≠ b ≠ c, α = β = γ = 90°)\n *\n * @remarks\n * The orthorhombic crystal system has:\n * - Three different edge lengths (a ≠ b ≠ c)\n * - All three angles equal to 90° (α = β = γ = 90°)\n * - Mutually perpendicular lattice vectors\n * - Orthorhombic point group symmetry\n *\n * This is one of the most common crystal systems in nature due to its lower symmetry\n * allowing for diverse crystal structures.\n *\n * Common examples of orthorhombic crystals:\n * - Sulfur (S) - α-sulfur\n * - Olivine [(Mg,Fe)₂SiO₄] - important mineral in Earth's mantle\n * - Aragonite (CaCO₃) - polymorph of calcite\n * - Cellulose - natural polymer\n * - Many organic crystals and pharmaceuticals\n *\n * @example\n * ```typescript\n * // Create an orthorhombic lattice (sulfur)\n * // S: a ≈ 10.47 Å, b ≈ 12.87 Å, c ≈ 24.39 Å\n * const lattice = orthorhombic(10.47, 12.87, 24.39);\n * const params = parameters(lattice);\n * // params ≈ [10.47, 12.87, 24.39, 90, 90, 90]\n * ```\n */\nexport function orthorhombic(a: number, b: number, c: number) {\n return fromParameters(a, b, c, 90, 90, 90);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates a rhombohedral (trigonal) lattice.\n *\n * @param a - Edge length (all three lattice vectors have equal length)\n * @param alpha - Angle between each pair of lattice vectors in **degrees**\n * (α = β = γ for the rhombohedral system)\n *\n * @returns A new Lattice object representing a rhombohedral crystal system\n * (a = b = c, α = β = γ ≠ 90°)\n *\n * @remarks\n * The rhombohedral (trigonal) crystal system has:\n * - Three equal edge lengths (a = b = c)\n * - Three equal angles (α = β = γ), all different from 90°\n * - All lattice vectors have the same relationship to each other\n * - High symmetry along the main diagonal\n *\n * The rhombohedral system is sometimes called \"trigonal\" in crystallographic notation,\n * though \"rhombohedral\" refers specifically to this lattice description.\n *\n * Common examples of rhombohedral crystals:\n * - Diamond (C) - when described in rhombohedral coordinates\n * - Calcite (CaCO₃) - trigonal form\n * - Hematite (Fe₂O₃) - iron oxide mineral\n * - Corundum (Al₂O₃) - includes ruby and sapphire\n * - Bismuth (Bi) - semimetal\n * - Many perovskite structures\n *\n * Note: A rhombohedral lattice can also be described as a hexagonal lattice under\n * certain conditions. The choice depends on the symmetry analysis of the structure.\n *\n * @example\n * ```typescript\n * // Create a rhombohedral lattice like diamond\n * // Diamond: a ≈ 3.567 Å, α ≈ 60° (for rhombohedral primitive cell)\n * const lattice = rhombohedral(3.567, 60);\n * const params = parameters(lattice);\n * // params ≈ [3.567, 3.567, 3.567, 60, 60, 60]\n *\n * // Create a rhombohedral lattice like calcite\n * // Calcite: a ≈ 3.029 Å, α ≈ 78.07° (rhombohedral primitive)\n * const calcite = rhombohedral(3.029, 78.07);\n * ```\n */\nexport function rhombohedral(a: number, alpha: number) {\n return fromParameters(a, a, a, alpha, alpha, alpha);\n}\n","import { fromParameters } from \"./fromParameters\";\n\n/**\n * Creates a tetragonal lattice.\n *\n * @param a - In-plane edge length (first two lattice vectors, a = b)\n * @param c - Out-of-plane edge length (third lattice vector)\n *\n * @returns A new Lattice object representing a tetragonal crystal system\n * (a = b ≠ c, α = β = γ = 90°)\n *\n * @remarks\n * The tetragonal crystal system has:\n * - Two equal edge lengths (a = b)\n * - Third edge length generally different (c ≠ a)\n * - All angles equal to 90° (α = β = γ = 90°)\n * - Mutually perpendicular lattice vectors\n * - Tetragonal point group symmetry (square base with different height)\n *\n * The tetragonal system can be viewed as a distorted cubic system where the\n * c-axis is either compressed or extended relative to the a-b plane.\n *\n * Common examples of tetragonal crystals:\n * - Tin (β-Sn) - white tin, body-centered tetragonal\n * - Rutile (TiO₂) - important mineral, used in pigments\n * - Indium (In) - body-centered tetragonal\n * - Many high-temperature superconductors (e.g., YBa₂Cu₃O₇)\n * - Zirconium dioxide (ZrO₂) - ceramic material\n *\n * @example\n * ```typescript\n * // Create a tetragonal lattice (rutile TiO₂)\n * // TiO₂: a ≈ 4.59 Å, c ≈ 2.96 Å\n * const lattice = tetragonal(4.59, 2.96);\n * const params = parameters(lattice);\n * // params ≈ [4.59, 4.59, 2.96, 90, 90, 90]\n * ```\n */\nexport function tetragonal(a: number, c: number) {\n return fromParameters(a, a, c, 90, 90, 90);\n}\n","import init, { analyze_cell, type MoyoDataset } from \"@spglib/moyo-wasm\";\n\nimport { createLattice } from \"@/core/lattice\";\nimport { Structure } from \"../../structure\";\n\nlet ready: Promise<void> | null = null;\n\n// Slightly awkward handling to manage node vs browser invocation (for tests...)\n/**\n * Initializes the Moyo WASM module for symmetry analysis.\n *\n * This function is called automatically by getSymmetry(), but can be called\n * explicitly to pre-load the module.\n *\n * @returns A Promise that resolves when the WASM module is ready\n * @throws Error if WASM loading fails\n *\n * @remarks\n * - Handles both Node.js (filesystem-based WASM loading) and browser environments\n * - Module is loaded only once; subsequent calls return the same promise\n * - Required for symmetry operations with spglib\n *\n * @example\n * ```typescript\n * // Pre-load WASM for faster first symmetry call\n * await initMoyo();\n * const symmetry = await getSymmetry(structure);\n * ```\n */\nexport function initMoyo() {\n if (!ready) {\n ready = (async () => {\n // In Node.js (tests), load from filesystem\n if (typeof process !== \"undefined\" && process.versions?.node) {\n try {\n const { readFileSync } = await import(\"fs\");\n const { join } = await import(\"path\");\n const wasmPath = join(\n process.cwd(),\n \"node_modules/@spglib/moyo-wasm/moyo_wasm_bg.wasm\",\n );\n const wasmBuffer = readFileSync(wasmPath);\n await init(wasmBuffer);\n } catch (e) {\n console.error(\"Failed to load WASM in Node:\", e);\n throw e;\n }\n } else {\n // In browser, use dynamic import to get the URL\n const wasmUrl = new URL(\n \"@spglib/moyo-wasm/moyo_wasm_bg.wasm\",\n import.meta.url,\n ).toString();\n\n await init(wasmUrl);\n }\n })();\n }\n return ready;\n}\n\n/**\n * Performs space group analysis on a crystal structure using spglib (Moyo WASM).\n *\n * Determines the symmetry of a structure and returns both the primitive and\n * conventional unit cells along with full symmetry analysis results.\n *\n * @param structure - The structure to analyze\n * @param tolerance - Symmetry tolerance in Ångströms (default: 1e-4)\n * @param setting - Choice of conventional cell setting (default: \"Standard\")\n * @returns An object containing:\n * - `primitive`: The primitive unit cell\n * - `conventional`: The conventional unit cell\n * - `calculationResults`: Raw spglib/Moyo analysis data\n * @throws Error if WASM initialization fails\n *\n * @remarks\n * - Requires initialization of WASM module (handled automatically)\n * - Converts between atomic symbols and numeric IDs for Moyo\n * - Works in both Node.js (file-based WASM) and browsers (URL-based)\n * - Computationally expensive for large structures\n * - Uses Moyo WASM for accurate, efficient symmetry analysis\n *\n * @example\n * ```typescript\n * const structure = { lattice: cubic(4.05), sites: [...] };\n * const symmetry = await getSymmetry(structure, 1e-4, \"Standard\");\n * console.log(symmetry.primitive);\n * console.log(symmetry.conventional);\n * ```\n */\nexport async function getSymmetry(\n structure: Structure,\n tolerance = 1e-4,\n setting = \"Standard\",\n): Promise<{\n primitive: Structure;\n conventional: Structure;\n calculationResults: any;\n}> {\n await initMoyo();\n\n // -----------------------------\n // 1. Build reversible mapping\n // -----------------------------\n const symbolToId = new Map<string, number>();\n const idToSymbol = new Map<number, string>();\n\n let counter = 0;\n\n const positions: number[][] = [];\n const numbers: number[] = [];\n\n for (const site of structure.sites) {\n const symbol = site.species.symbol;\n\n if (!symbolToId.has(symbol)) {\n symbolToId.set(symbol, counter);\n idToSymbol.set(counter, symbol);\n counter++;\n }\n\n positions.push(Array.from(site.frac));\n numbers.push(symbolToId.get(symbol)!);\n }\n\n // -----------------------------\n // 2. Build Moyo input\n // -----------------------------\n const moyoInput = {\n lattice: {\n basis: Array.from(structure.lattice.basis.data),\n },\n positions,\n numbers,\n };\n\n // -----------------------------\n // 3. Run symmetry engine\n // -----------------------------\n const results = await analyze_cell(\n JSON.stringify(moyoInput),\n tolerance,\n setting,\n );\n\n // -----------------------------\n // 4. Convert Moyo cell → Structure\n // -----------------------------\n function build(cell: {\n lattice: { basis: number[] };\n positions: number[][];\n numbers: number[];\n }): Structure {\n const { lattice, positions, numbers } = cell;\n\n const species = [...new Set(numbers)].map((n: number) => ({\n symbol: idToSymbol.get(n)!,\n }));\n\n const sites = positions.map((pos: number[], i: number) => ({\n species: {\n symbol: idToSymbol.get(numbers[i])!,\n },\n frac: new Float64Array(pos),\n }));\n\n return {\n lattice: createLattice(lattice.basis),\n species,\n sites,\n };\n }\n\n // -----------------------------\n // 5. Return both structures\n // -----------------------------\n return {\n primitive: build(results.prim_std_cell),\n conventional: build(results.std_cell),\n calculationResults: results,\n };\n}\n","import { createLattice } from \"@/core/lattice/lattice\";\nimport type { Structure } from \"../structure\";\nimport type { Site } from \"@/core/site/site\";\n\ntype SupercellSize = number | [number, number, number];\n\n/**\n * Creates a supercell by repeating the structure a specified number of times.\n *\n * Expands the unit cell along one or more directions, creating a larger supercell\n * with multiple copies of each atom. The fractional coordinates are updated accordingly.\n *\n * @param structure - The original structure\n * @param size - Number of repetitions: either a single number (uniform) or [nx, ny, nz]\n * @returns A new structure with the supercell and duplicated atoms\n * @throws Error if supercell dimensions are not positive integers\n *\n * @remarks\n * - Lattice basis vectors are scaled by the repetition factors\n * - Each atom is copied to all equivalent positions in the supercell\n * - Fractional coordinates are scaled accordingly (position / repetition)\n * - Useful for calculating properties that require larger cells\n * - Equivalent to a k-point mesh reduction in some contexts\n *\n * @example\n * ```typescript\n * const structure = {\n * lattice: cubic(3.14),\n * sites: [{ species: 'Fe', frac: [0, 0, 0] }]\n * };\n *\n * // Create 2×2×2 supercell (8 atoms total)\n * const super2x2x2 = supercell(structure, 2);\n *\n * // Create 2×3×2 supercell (asymmetric)\n * const superAsym = supercell(structure, [2, 3, 2]);\n * ```\n */\nexport function supercell(\n structure: Structure,\n size: SupercellSize,\n): Structure {\n const [nx, ny, nz] = typeof size === \"number\" ? [size, size, size] : size;\n\n if (\n nx < 1 ||\n ny < 1 ||\n nz < 1 ||\n !Number.isInteger(nx) ||\n !Number.isInteger(ny) ||\n !Number.isInteger(nz)\n ) {\n throw new Error(\"Supercell dimensions must be positive integers\");\n }\n\n const m = structure.lattice.basis.data;\n\n // row-major scaling\n const newBasis = [\n m[0] * nx,\n m[1] * nx,\n m[2] * nx,\n\n m[3] * ny,\n m[4] * ny,\n m[5] * ny,\n\n m[6] * nz,\n m[7] * nz,\n m[8] * nz,\n ];\n\n const sites: Site[] = [];\n\n for (const site of structure.sites) {\n const [x, y, z] = site.frac;\n\n for (let i = 0; i < nx; i++) {\n for (let j = 0; j < ny; j++) {\n for (let k = 0; k < nz; k++) {\n sites.push({\n species: site.species,\n\n frac: new Float64Array([(x + i) / nx, (y + j) / ny, (z + k) / nz]),\n });\n }\n }\n }\n }\n\n return {\n lattice: createLattice(newBasis),\n sites,\n };\n}\n","import { Species } from \"../species/species\";\n\nexport type SiteProperties = Record<string, any>;\n\nexport type Vec3 = [number, number, number] | Float64Array | number[];\n\nexport type Site<P extends SiteProperties = SiteProperties> = {\n species: Species;\n frac: Vec3;\n properties?: P;\n};\n\nexport function createSite<P extends SiteProperties>(\n species: Species,\n frac: Vec3,\n properties?: P,\n): Site<P> {\n return {\n species,\n frac,\n properties,\n };\n}\n","import { mul } from \"../matrix/operations/mul\";\nimport { Site } from \"./site\";\nimport { Lattice } from \"../lattice/lattice\";\nimport { Vector } from \"../matrix/vector\";\n\nexport function cartesian(lattice: Lattice, site: Site): Vector {\n const [x, y, z] = site.frac;\n\n const frac = {\n rows: 3,\n cols: 1,\n data: new Float64Array([x, y, z]),\n };\n\n const result = mul(lattice.basis, frac);\n\n return new Float64Array([result.data[0], result.data[1], result.data[2]]);\n}\n","import { inverse } from \"../lattice/inverse\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { Vector } from \"../matrix/vector\";\nimport { Lattice } from \"../lattice/lattice\";\n\nexport function fractional(lattice: Lattice, cart: Vector): Vector {\n const vec = {\n rows: 3,\n cols: 1,\n data: cart,\n };\n\n const inv = inverse(lattice);\n\n const result = mul(inv, vec);\n\n return new Float64Array([result.data[0], result.data[1], result.data[2]]);\n}\n","import { Lattice } from \"../lattice/lattice\";\nimport { Site } from \"./site\";\nimport { cartesian } from \"./cartesian\";\n\nimport { norm } from \"../matrix/operations/vector/norm\";\n\nexport function distance(lattice: Lattice, a: Site, b: Site): number {\n const dFrac: [number, number, number] = [\n b.frac[0] - a.frac[0],\n b.frac[1] - a.frac[1],\n b.frac[2] - a.frac[2],\n ];\n\n for (let i = 0; i < 3; i++) {\n dFrac[i] -= Math.round(dFrac[i]);\n }\n\n const displaced: Site = {\n species: a.species,\n frac: dFrac,\n };\n\n const dCart = cartesian(lattice, displaced);\n\n return norm(dCart);\n}\n","import { Site, SiteProperties } from \"./site\";\n\nfunction wrapValue(x: number): number {\n return ((x % 1) + 1) % 1;\n}\n\nexport function wrap<T extends SiteProperties>(site: Site<T>): Site<T> {\n return {\n ...site,\n frac: [\n wrapValue(site.frac[0]),\n wrapValue(site.frac[1]),\n wrapValue(site.frac[2]),\n ],\n };\n}\n","export type Species<P extends Record<string, any> = Record<string, any>> = {\n symbol: string;\n properties?: P;\n};\n\nexport function createSpecies<P extends Record<string, any>>(\n symbol: string,\n properties?: P,\n): Species<P> {\n return { symbol, properties };\n}\n","import { fromParameters } from \"../lattice/create/fromParameters\";\nimport { parameters } from \"../lattice/parameters\";\nimport { Structure } from \"../structure/structure\";\n\nfunction cleanValue(value: string): number {\n // remove uncertainty notation:\n // 5.432(1) -> 5.432\n return Number(value.replace(/\\(.+\\)/, \"\"));\n}\n\nfunction tokenize(line: string): string[] {\n return line.match(/'[^']*'|\"[^\"]*\"|\\S+/g) ?? [];\n}\n\nfunction warnUnsupportedSymmetry(spaceGroup: string) {\n console.warn(\n `Space group \"${spaceGroup}\" detected. ` +\n `Symmetry operations are not currently applied; ` +\n `only asymmetric-unit sites will be parsed.`,\n );\n}\n\n/**\n * Parses a crystal structure from CIF (Crystallographic Information File) format.\n *\n * Extracts lattice parameters, atomic positions, and species information from a CIF file.\n * Assumes the file contains a single crystal structure block.\n *\n * @param text - The CIF file content as a string\n * @returns A Structure object parsed from the CIF data\n * @throws Error if required CIF fields are missing\n *\n * @remarks\n * - Currently reads only the asymmetric unit (symmetry operations are NOT applied)\n * - Warnings are issued if space group symmetry information is detected but not used\n * - Uncertainty values in CIF are stripped (e.g., 5.432(1) → 5.432)\n * - Only the first data block is processed\n * - Supports quoted values and multiple formatting styles\n *\n * @example\n * ```typescript\n * const cifText = `\n * data_structure\n * _cell_length_a 4.05\n * _cell_length_b 4.05\n * _cell_length_c 4.05\n * _cell_angle_alpha 90\n * _cell_angle_beta 90\n * _cell_angle_gamma 90\n * _atom_site_label Al1\n * _atom_site_fract_x 0\n * _atom_site_fract_y 0\n * _atom_site_fract_z 0\n * `;\n * const structure = fromCIF(cifText);\n * ```\n */\nexport function fromCIF(text: string): Structure {\n const lines = text\n .split(\"\\n\")\n .map((x) => x.trim())\n .filter(Boolean);\n\n let a = 0;\n let b = 0;\n let c = 0;\n\n let alpha = 0;\n let beta = 0;\n let gamma = 0;\n\n let spaceGroup = \"P1\";\n\n let atomHeaders: string[] = [];\n const atomRows: string[][] = [];\n\n let inLoop = false;\n let currentHeaders: string[] = [];\n let collectingAtoms = false;\n\n for (const line of lines) {\n if (line.startsWith(\"_symmetry_space_group_name_H-M\")) {\n const tokens = tokenize(line);\n spaceGroup = tokens.at(-1)?.replace(/['\"]/g, \"\") ?? \"P1\";\n } else if (line.startsWith(\"_space_group_name_H-M_alt\")) {\n const tokens = tokenize(line);\n spaceGroup = tokens.at(-1)?.replace(/['\"]/g, \"\") ?? \"P1\";\n } else if (line.startsWith(\"_cell_length_a\")) {\n a = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_length_b\")) {\n b = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_length_c\")) {\n c = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_alpha\")) {\n alpha = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_beta\")) {\n beta = cleanValue(tokenize(line)[1]);\n } else if (line.startsWith(\"_cell_angle_gamma\")) {\n gamma = cleanValue(tokenize(line)[1]);\n } else if (line === \"loop_\") {\n inLoop = true;\n currentHeaders = [];\n collectingAtoms = false;\n continue;\n }\n\n if (inLoop && line.startsWith(\"_\")) {\n currentHeaders.push(line);\n\n if (line.includes(\"_atom_site_\")) {\n collectingAtoms = true;\n }\n\n continue;\n }\n\n if (inLoop && collectingAtoms) {\n if (atomHeaders.length === 0) {\n atomHeaders = [...currentHeaders];\n }\n\n atomRows.push(tokenize(line));\n }\n }\n\n const isP1 = /^P\\s*1$/i.test(spaceGroup);\n\n if (!isP1) {\n warnUnsupportedSymmetry(spaceGroup);\n }\n\n const lattice = fromParameters(a, b, c, alpha, beta, gamma);\n\n const ix = atomHeaders.findIndex((x) => x.includes(\"fract_x\"));\n\n const iy = atomHeaders.findIndex((x) => x.includes(\"fract_y\"));\n\n const iz = atomHeaders.findIndex((x) => x.includes(\"fract_z\"));\n\n const ispecies = atomHeaders.findIndex((x) => x.includes(\"type_symbol\"));\n\n if (ix < 0 || iy < 0 || iz < 0 || ispecies < 0) {\n throw new Error(\"Missing required atom site columns\");\n }\n\n const sites = atomRows.map((row) => ({\n species: {\n symbol: row[ispecies],\n },\n\n frac: new Float64Array([\n cleanValue(row[ix]),\n cleanValue(row[iy]),\n cleanValue(row[iz]),\n ]),\n }));\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toCIF(structure: Structure, precision = 6): string {\n const p = parameters(structure.lattice);\n\n const lines: string[] = [];\n\n lines.push(\"data_matsci-parse\");\n lines.push(\"\");\n\n lines.push(\"_symmetry_space_group_name_H-M 'P 1'\");\n lines.push(\"_symmetry_Int_Tables_number 1\");\n\n lines.push(\"\");\n\n lines.push(`_cell_length_a ${p[0].toFixed(precision)}`);\n\n lines.push(`_cell_length_b ${p[1].toFixed(precision)}`);\n\n lines.push(`_cell_length_c ${p[2].toFixed(precision)}`);\n\n lines.push(`_cell_angle_alpha ${p[3].toFixed(precision)}`);\n\n lines.push(`_cell_angle_beta ${p[4].toFixed(precision)}`);\n\n lines.push(`_cell_angle_gamma ${p[5].toFixed(precision)}`);\n\n lines.push(\"\");\n\n lines.push(\"loop_\");\n lines.push(\"_atom_site_label\");\n lines.push(\"_atom_site_type_symbol\");\n lines.push(\"_atom_site_fract_x\");\n lines.push(\"_atom_site_fract_y\");\n lines.push(\"_atom_site_fract_z\");\n\n for (let i = 0; i < structure.sites.length; i++) {\n const site = structure.sites[i];\n\n lines.push(\n `${site.species.symbol}${i + 1} ` +\n `${site.species.symbol} ` +\n `${site.frac[0].toFixed(precision)} ` +\n `${site.frac[1].toFixed(precision)} ` +\n `${site.frac[2].toFixed(precision)}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n","import { createLattice } from \"../lattice/lattice\";\nimport { inverse } from \"../lattice/inverse\";\nimport { mul } from \"../matrix/operations/mul\";\nimport { createMatrix } from \"../matrix/matrix\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\nimport { fractional } from \"../site/fractional\";\n\nimport { cartesian } from \"../site\";\n\nfunction isSelective(line: string): boolean {\n return line.toLowerCase().startsWith(\"selective\");\n}\n\nfunction isCartesian(line: string): boolean {\n const l = line.trim().toLowerCase();\n return l.startsWith(\"c\") || l.startsWith(\"k\");\n}\n\n// TODO: Currently nukes the selective dynamics flag from the input file.\n// It would be good to restore this.\n// TODO: would be good to ensure that the title is also optionally\n// maintained.\n/**\n * Parses a crystal structure from POSCAR (VASP) format.\n *\n * Reads lattice vectors, atomic positions, and species from VASP's POSCAR/CONTCAR format.\n * Supports both Cartesian and fractional coordinates.\n *\n * @param text - The POSCAR file content as a string\n * @returns A Structure object parsed from the POSCAR data\n * @throws Error if required POSCAR fields are missing or malformed\n *\n * @remarks\n * - Line 1: Comment/title line (ignored)\n * - Line 2: Scaling factor\n * - Lines 3-5: Lattice vectors (in Ångströms or scaled units)\n * - Line 6: Element symbols\n * - Line 7: Number of atoms per element\n * - Line 8+: Atomic positions (Cartesian or fractional)\n * - Selective dynamics flags are currently stripped\n * - Structure title is not preserved in the output\n *\n * @example\n * ```typescript\n * const poscarText = `Cubic structure\n * 1.0\n * 4.05 0 0\n * 0 4.05 0\n * 0 0 4.05\n * Al\n * 2\n * Fractional\n * 0 0 0\n * 0.5 0.5 0.5`;\n * const structure = fromPOSCAR(poscarText);\n * ```\n */\nexport function fromPOSCAR(text: string): Structure {\n const lines = text.split(\"\\n\").map((x) => x.trim());\n\n let cursor = 0;\n\n // comment/title\n cursor++;\n\n // scale factor\n const scale = Number(lines[cursor++]);\n\n // lattice vectors (row-major)\n const latticeData: number[] = [];\n\n for (let i = 0; i < 3; i++) {\n const v = lines[cursor++].split(/\\s+/).map(Number);\n\n if (v.length !== 3) {\n throw new Error(\"Invalid POSCAR lattice\");\n }\n\n latticeData.push(v[0] * scale, v[1] * scale, v[2] * scale);\n }\n\n const lattice = createLattice(latticeData);\n\n // VASP5 species names\n const symbols = lines[cursor++].split(/\\s+/);\n\n // atom counts\n const counts = lines[cursor++].split(/\\s+/).map(Number);\n\n if (symbols.length !== counts.length) {\n throw new Error(\"Species/count mismatch\");\n }\n\n // optional selective dynamics\n if (isSelective(lines[cursor])) {\n cursor++;\n }\n\n // direct is true unless cartesian is.\n let direct = true;\n direct = !isCartesian(lines[cursor]);\n\n cursor++;\n\n const sites: Site[] = [];\n\n let speciesIndex = 0;\n let remaining = counts[0];\n\n const latticeInv = !direct ? inverse(lattice) : null;\n\n const totalAtoms = counts.reduce((a, b) => a + b, 0);\n\n for (let i = 0; i < totalAtoms; i++) {\n const tokens = lines[cursor++].split(/\\s+/);\n\n const coords = tokens.slice(0, 3).map(Number);\n\n const frac = direct\n ? new Float64Array(coords)\n : fractional(lattice, new Float64Array(coords));\n\n sites.push({\n species: {\n symbol: symbols[speciesIndex],\n },\n frac,\n });\n\n remaining--;\n\n if (remaining === 0 && speciesIndex < counts.length - 1) {\n speciesIndex++;\n remaining = counts[speciesIndex];\n }\n }\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toPOSCAR(\n structure: Structure,\n options?: {\n title?: string;\n scale?: number;\n direct?: boolean;\n },\n): string {\n const title = options?.title ?? \"Generated by matsci-parse\";\n const scale = options?.scale ?? 1.0;\n const direct = options?.direct ?? true;\n\n const lines: string[] = [];\n\n lines.push(title);\n lines.push(String(scale));\n\n // lattice\n const m = structure.lattice.basis.data;\n\n lines.push(`${m[0]} ${m[1]} ${m[2]}`);\n lines.push(`${m[3]} ${m[4]} ${m[5]}`);\n lines.push(`${m[6]} ${m[7]} ${m[8]}`);\n\n // preserve order of first appearance\n const grouped = new Map<string, typeof structure.sites>();\n\n for (const site of structure.sites) {\n const symbol = site.species.symbol;\n\n if (!grouped.has(symbol)) {\n grouped.set(symbol, []);\n }\n\n grouped.get(symbol)!.push(site);\n }\n\n const species = [...grouped.keys()];\n const sites = [...grouped.values()].flat();\n\n lines.push(species.join(\" \"));\n lines.push(species.map((s) => grouped.get(s)!.length).join(\" \"));\n\n lines.push(direct ? \"Direct\" : \"Cartesian\");\n\n for (const site of sites) {\n const coords = direct ? site.frac : cartesian(structure.lattice, site);\n\n lines.push(`${coords[0]} ${coords[1]} ${coords[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import { Structure } from \"../structure/structure\";\nimport { createLattice } from \"../lattice/lattice\";\n\nimport { cartesian } from \"../site/cartesian\";\nimport { fractional } from \"../site/fractional\";\n\nexport interface AiiDASite {\n position: [number, number, number];\n symbols: string[];\n}\n\nexport interface StructureData {\n cell: [\n [number, number, number],\n [number, number, number],\n [number, number, number],\n ];\n kinds: [];\n sites: AiiDASite[];\n}\n\n/**\n * Parses a crystal structure from AiiDA/StructureData representation.\n *\n * Converts AiiDA StructureData format to a Structure object.\n * Used for compatibility with AiiDA workflows.\n *\n * @param data - An AiiDA StructureData object with `cell` (3×3) and `sites` array\n * @returns A new Structure object\n * @throws Error if cell or sites data is malformed\n *\n * @remarks\n * - `cell`: 3×3 array of Cartesian lattice vectors\n * - `sites`: Array of AiiDASite objects with position and species\n * - `kinds`: Array defining species information (symbol mapping)\n * - Converts Cartesian coordinates to fractional internally\n * - Used primarily for VASP and other DFT workflow integration\n *\n * @example\n * ```typescript\n * const aiidaData = {\n * cell: [[4.05, 0, 0], [0, 4.05, 0], [0, 0, 4.05]],\n * kinds: [{ name: 'Al', symbol: 'Al' }],\n * sites: [\n * { position: [0, 0, 0], symbols: ['Al'] },\n * { position: [2.025, 2.025, 2.025], symbols: ['Al'] }\n * ]\n * };\n * const structure = fromStructureData(aiidaData);\n * ```\n */\nexport function fromStructureData(data: StructureData): Structure {\n const lattice = createLattice([\n ...data.cell[0],\n ...data.cell[1],\n ...data.cell[2],\n ]);\n\n const kindMap = new Map(data.kinds.map((kind: any) => [kind.name, kind]));\n\n const sites = data.sites.map((site: any) => {\n const kind = kindMap.get(site.kind_name);\n\n if (!kind) {\n throw new Error(`Unknown kind \"${site.kind_name}\"`);\n }\n\n return {\n species: {\n symbol: kind.symbols[0],\n },\n\n frac: fractional(lattice, new Float64Array(site.position)),\n };\n });\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toStructureData(structure: Structure) {\n const m = structure.lattice.basis.data;\n\n const symbols = [...new Set(structure.sites.map((s) => s.species.symbol))];\n\n const kinds = symbols.map((symbol) => ({\n name: symbol,\n symbols: [symbol],\n }));\n\n return {\n cell: [\n [m[0], m[1], m[2]],\n [m[3], m[4], m[5]],\n [m[6], m[7], m[8]],\n ],\n\n kinds,\n\n sites: structure.sites.map((site) => ({\n kind_name: site.species.symbol,\n\n position: Array.from(cartesian(structure.lattice, site)),\n })),\n\n pbc1: true,\n pbc2: true,\n pbc3: true,\n };\n}\n","import { createLattice } from \"../lattice/lattice\";\nimport { fractional } from \"../site/fractional\";\nimport { cartesian } from \"../site/cartesian\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\n\nfunction findSection(lines: string[], section: string): number {\n const idx = lines.findIndex((line) => line.trim().toUpperCase() === section);\n\n if (idx === -1) {\n throw new Error(`Missing ${section}`);\n }\n\n return idx;\n}\n\n// TODO: support atomic numbers instead of symbols in primvec.\n\n/**\n * Parses a crystal structure from XSF (XCrySDen Structure File) format.\n *\n * Reads lattice vectors and atomic positions from XSF format.\n * Supports both PRIMVEC (primitive) and CONVVEC (conventional) cells.\n *\n * @param text - The XSF file content as a string\n * @returns A Structure object parsed from the XSF data\n * @throws Error if required sections (PRIMVEC, ATOMS) are missing\n *\n * @remarks\n * - XSF format is human-readable and widely used in visualization software\n * - PRIMVEC section defines the lattice vectors\n * - ATOMS section lists atomic positions and species\n * - Atomic numbers are currently not supported (symbols required)\n * - CONVVEC (conventional cell) is not currently used\n *\n * @example\n * ```typescript\n * const xsfText = `\n * PRIMVEC\n * 4.05 0.00 0.00\n * 0.00 4.05 0.00\n * 0.00 0.00 4.05\n * PRIMCOORD\n * 2 1\n * Al 0.00 0.00 0.00 0 0 0\n * Al 2.025 2.025 2.025 0 0 0\n * `;\n * const structure = fromXSF(xsfText);\n * ```\n */\nexport function fromXSF(text: string): Structure {\n const lines = text\n .split(\"\\n\")\n .map((x) => x.trim())\n .filter(Boolean);\n\n const vecStart = findSection(lines, \"PRIMVEC\");\n\n const lattice = createLattice([\n ...lines[vecStart + 1].split(/\\s+/).map(Number),\n ...lines[vecStart + 2].split(/\\s+/).map(Number),\n ...lines[vecStart + 3].split(/\\s+/).map(Number),\n ]);\n\n const coordStart = findSection(lines, \"PRIMCOORD\");\n\n const [nAtoms] = lines[coordStart + 1].split(/\\s+/).map(Number);\n\n const sites: Site[] = [];\n\n for (let i = 0; i < nAtoms; i++) {\n const tokens = lines[coordStart + 2 + i].split(/\\s+/);\n\n const symbol = tokens[0];\n\n const x = Number(tokens[1]);\n const y = Number(tokens[2]);\n const z = Number(tokens[3]);\n\n const frac = fractional(lattice, new Float64Array([x, y, z]));\n\n sites.push({\n species: { symbol },\n frac,\n });\n }\n\n return {\n lattice,\n sites,\n };\n}\n\nfunction formatVec(v: number[]): string {\n return `${v[0]} ${v[1]} ${v[2]}`;\n}\n\nfunction formatLattice(lattice: Structure[\"lattice\"]): string[] {\n const m = lattice.basis.data;\n\n return [\n formatVec([m[0], m[1], m[2]]),\n formatVec([m[3], m[4], m[5]]),\n formatVec([m[6], m[7], m[8]]),\n ];\n}\n\nexport function toXSF(structure: Structure): string {\n const lines: string[] = [];\n\n lines.push(\"CRYSTAL\");\n lines.push(\"PRIMVEC\");\n\n const latticeLines = formatLattice(structure.lattice);\n lines.push(...latticeLines);\n\n lines.push(\"\");\n lines.push(\"PRIMCOORD\");\n lines.push(`${structure.sites.length} 1`);\n\n for (const site of structure.sites) {\n const c = cartesian(structure.lattice, site);\n\n lines.push(`${site.species.symbol} ${c[0]} ${c[1]} ${c[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import { createLattice, Lattice } from \"../lattice/lattice\";\nimport { Site } from \"../site/site\";\nimport { Structure } from \"../structure/structure\";\n\ntype ExtendedXYZInfo = Record<string, string>;\n\nfunction parseHeader(comment: string): ExtendedXYZInfo {\n const info: ExtendedXYZInfo = {};\n const kvRegex = /(\\w+)=(\".*?\"|\\S+)/g;\n\n for (const match of comment.matchAll(kvRegex)) {\n let value = match[2];\n if (value.startsWith('\"')) value = value.slice(1, -1);\n info[match[1]] = value;\n }\n\n return info;\n}\n\nfunction parseLattice(info: ExtendedXYZInfo) {\n if (!info.Lattice) {\n throw new Error(\"Extended XYZ must contain Lattice\");\n }\n\n const v = info.Lattice.split(/\\s+/).map(Number);\n if (v.length !== 9) throw new Error(\"Invalid Lattice\");\n\n return createLattice([v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]]);\n}\n\n/**\n * Parses a crystal structure from extended XYZ format.\n *\n * Reads atomic structure from XYZ format with extended headers containing\n * lattice information (Extended XYZ format used by ASE and other tools).\n *\n * @param text - The XYZ file content as a string\n * @returns A Structure object parsed from the XYZ data\n * @throws Error if lattice information or required fields are missing\n *\n * @remarks\n * - First line: number of atoms\n * - Second line: properties header in key=value format (must include \"Lattice\")\n * - Remaining lines: atomic species and Cartesian positions\n * - Lattice must be specified in extended header as 9 space-separated values\n * - Standard XYZ format (without lattice) is not supported\n *\n * @example\n * ```typescript\n * const xyzText = `2\n * Lattice=\"4.05 0 0 0 4.05 0 0 0 4.05\" Properties=species:S:1:pos:R:3\n * Al 0.0 0.0 0.0\n * Al 2.025 2.025 2.025`;\n * const structure = fromXYZ(xyzText);\n * ```\n */\nexport function fromXYZ(text: string) {\n const lines = text.trim().split(\"\\n\");\n\n const n = Number(lines[0]);\n const comment = lines[1];\n\n const info = parseHeader(comment);\n const lattice = parseLattice(info);\n\n const sites: Site[] = [];\n\n for (let i = 0; i < n; i++) {\n const [symbol, x, y, z] = lines[2 + i].split(/\\s+/);\n\n sites.push({\n species: { symbol },\n frac: new Float64Array([+x, +y, +z]),\n });\n }\n\n return { lattice, sites };\n}\n\nfunction formatLattice(lattice: Lattice): string {\n const m = lattice.basis.data;\n\n // row-major flattening assumption (consistent with your matrix code)\n return `${m[0]} ${m[1]} ${m[2]} ${m[3]} ${m[4]} ${m[5]} ${m[6]} ${m[7]} ${m[8]}`;\n}\n\n/**\n * Serializes a structure to extended XYZ format.\n *\n * Converts a Structure to extended XYZ format suitable for visualization\n * and exchange with other materials science tools (ASE, OVITO, etc.).\n *\n * @param structure - The structure to serialize\n * @returns The structure as an extended XYZ formatted string\n *\n * @remarks\n * - Line 1: Number of atoms\n * - Line 2: Header with lattice information in extended XYZ format\n * - Remaining lines: Atomic species and fractional coordinates\n * - Lattice is specified as 9 space-separated values in row-major order\n * - The output uses fractional coordinates as given in the structure\n *\n * @example\n * ```typescript\n * const structure = { lattice: cubic(4.05), sites: [...] };\n * const xyzString = toXYZ(structure);\n * // Output can be written to file and opened in visualization software\n * ```\n */\nexport function toXYZ(structure: Structure): string {\n const sites = structure.sites;\n\n const lines: string[] = [];\n\n lines.push(String(sites.length));\n\n const latticeStr = formatLattice(structure.lattice);\n\n lines.push(`Lattice=\"${latticeStr}\"`);\n\n for (const site of sites) {\n const f = site.frac;\n\n lines.push(`${site.species.symbol} ${f[0]} ${f[1]} ${f[2]}`);\n }\n\n return lines.join(\"\\n\");\n}\n","import { createLattice } from \"../lattice\";\n\nimport { fractional, cartesian } from \"../site\";\nimport { Structure } from \"../structure\";\n\nexport function fromOptimade(data: any): Structure {\n const lattice = createLattice([\n ...data.attributes.lattice_vectors[0],\n ...data.attributes.lattice_vectors[1],\n ...data.attributes.lattice_vectors[2],\n ]);\n\n const positions = data.attributes.cartesian_site_positions;\n const species = data.attributes.species_at_sites;\n\n const sites = positions.map((position: number[], i: number) => ({\n species: {\n symbol: species[i],\n },\n\n frac: fractional(lattice, new Float64Array(position)),\n }));\n\n return {\n lattice,\n sites,\n };\n}\n\nexport function toOptimade(structure: Structure) {\n const m = structure.lattice.basis.data;\n\n const species_at_sites = structure.sites.map((site) => site.species.symbol);\n\n const elements = [...new Set(species_at_sites)].sort();\n\n return {\n attributes: {\n lattice_vectors: [\n [m[0], m[1], m[2]],\n [m[3], m[4], m[5]],\n [m[6], m[7], m[8]],\n ],\n\n species_at_sites,\n\n cartesian_site_positions: structure.sites.map((site) =>\n Array.from(cartesian(structure.lattice, site)),\n ),\n\n dimension_types: [1, 1, 1],\n\n nsites: structure.sites.length,\n\n nelements: elements.length,\n\n elements,\n },\n };\n}\n","import { Structure } from \"../structure/structure\";\nimport { createLattice } from \"../lattice/lattice\";\n\n/**\n * Serializes a structure to JSON format.\n *\n * Converts a Structure to a plain JavaScript object suitable for JSON stringification.\n *\n * @param structure - The structure to serialize\n * @returns An object with `lattice` (flattened array) and `sites` (with species and fractional coordinates)\n *\n * @remarks\n * - Lattice is serialized as a flat array [a1x, a1y, a1z, ...]\n * - Fractional coordinates are converted from Float64Array to regular arrays\n * - Use with JSON.stringify() for string serialization\n *\n * @example\n * ```typescript\n * const structure = { lattice: cubic(4), sites: [...] };\n * const json = toJSON(structure);\n * const jsonString = JSON.stringify(json);\n * ```\n */\nexport function toJSON(structure: Structure) {\n return {\n lattice: structure.lattice.basis.data,\n sites: structure.sites.map((s) => ({\n species: s.species,\n frac: Array.from(s.frac),\n })),\n };\n}\n\n/**\n * Deserializes a structure from JSON format.\n *\n * Reconstructs a Structure from a JSON object (typically parsed from JSON string).\n *\n * @param data - An object with `lattice` (9-element array) and `sites` array\n * @returns A new Structure object\n *\n * @remarks\n * - Lattice array must have exactly 9 elements\n * - Fractional coordinates are converted to Float64Array\n * - Inverse operation of toJSON()\n * - No validation is performed on the input data\n *\n * @example\n * ```typescript\n * const jsonData = {\n * lattice: [4, 0, 0, 0, 4, 0, 0, 0, 4],\n * sites: [{ species: 'Al', frac: [0, 0, 0] }]\n * };\n * const structure = fromJSON(jsonData);\n * ```\n */\nexport function fromJSON(data: any): Structure {\n return {\n lattice: createLattice(data.lattice),\n sites: data.sites.map((s: any) => ({\n species: s.species,\n frac: new Float64Array(s.frac),\n })),\n };\n}\n","export function convertMeasurement<T extends string>(\n value: number,\n from: T,\n to: T,\n conversions: Record<T, number>,\n aliases?: Record<string, T>,\n): number {\n const resolve = (u: string) => (aliases?.[u] ?? u) as T;\n\n const fromUnit = resolve(from);\n const toUnit = resolve(to);\n\n if (fromUnit === toUnit) return value;\n\n const valueInBase = value * conversions[fromUnit];\n return valueInBase / conversions[toUnit];\n}\n\nexport function convertMeasurementArray<T extends string>(\n arr: number[],\n from: T,\n to: T,\n conversions: Record<T, number>,\n aliases?: Record<string, T>,\n): number[] {\n return arr.map((v) => convertMeasurement(v, from, to, conversions, aliases));\n}\n","import { convertMeasurement, convertMeasurementArray } from \"./converter\";\n\nexport type LengthUnits =\n | \"angstrom\"\n | \"bohr\"\n | \"nm\"\n | \"pm\"\n | \"cm\"\n | \"m\"\n | \"um\"\n | \"fm\";\n\nconst LengthConversions: Record<LengthUnits, number> = {\n angstrom: 1,\n bohr: 0.529177,\n nm: 10,\n pm: 0.01,\n um: 1e4,\n cm: 1e8,\n m: 1e10,\n fm: 1e-5,\n};\n\nconst LengthAliases: Record<string, LengthUnits> = {\n Å: \"angstrom\",\n μm: \"um\",\n};\n\nexport const LengthUnitSystem = {\n conversions: LengthConversions,\n aliases: LengthAliases,\n\n convert(value: number, from: LengthUnits | string, to: LengthUnits | string) {\n return convertMeasurement(\n value,\n from as LengthUnits,\n to as LengthUnits,\n LengthConversions,\n LengthAliases,\n );\n },\n\n convertArray(\n arr: number[],\n from: LengthUnits | string,\n to: LengthUnits | string,\n ) {\n return convertMeasurementArray(\n arr,\n from as LengthUnits,\n to as LengthUnits,\n LengthConversions,\n LengthAliases,\n );\n },\n};\n","import { convertMeasurement, convertMeasurementArray } from \"./converter\";\n\nexport type EnergyUnits = \"eV\" | \"Hartree\" | \"kJ/mol\" | \"kcal/mol\";\n\nconst EnergyConversions: Record<EnergyUnits, number> = {\n eV: 1,\n Hartree: 27.2114,\n \"kJ/mol\": 0.0103643,\n \"kcal/mol\": 0.0433641,\n};\n\nconst EnergyAliases: Record<string, EnergyUnits> = {\n Ha: \"Hartree\",\n ev: \"eV\",\n electronvolt: \"eV\",\n};\n\nexport const EnergyUnitSystem = {\n conversions: EnergyConversions,\n aliases: EnergyAliases,\n\n convert(value: number, from: EnergyUnits | string, to: EnergyUnits | string) {\n return convertMeasurement(\n value,\n from as EnergyUnits,\n to as EnergyUnits,\n EnergyConversions,\n EnergyAliases,\n );\n },\n\n convertArray(\n arr: number[],\n from: EnergyUnits | string,\n to: EnergyUnits | string,\n ) {\n return convertMeasurementArray(\n arr,\n from as EnergyUnits,\n to as EnergyUnits,\n EnergyConversions,\n EnergyAliases,\n );\n },\n};\n","import { convertMeasurement, convertMeasurementArray } from \"./converter\";\n\nexport type AngleUnits = \"rad\" | \"deg\" | \"grad\";\n\nconst AngleConversions: Record<AngleUnits, number> = {\n rad: 1,\n deg: Math.PI / 180,\n grad: Math.PI / 200,\n};\n\nconst AngleAliases: Record<string, AngleUnits> = {\n \"°\": \"deg\",\n deg: \"deg\",\n rad: \"rad\",\n gon: \"grad\",\n};\n\nexport const AngleUnitSystem = {\n conversions: AngleConversions,\n aliases: AngleAliases,\n\n convert(value: number, from: AngleUnits | string, to: AngleUnits | string) {\n return convertMeasurement(\n value,\n from as AngleUnits,\n to as AngleUnits,\n AngleConversions,\n AngleAliases,\n );\n },\n\n convertArray(\n arr: number[],\n from: AngleUnits | string,\n to: AngleUnits | string,\n ) {\n return convertMeasurementArray(\n arr,\n from as AngleUnits,\n to as AngleUnits,\n AngleConversions,\n AngleAliases,\n );\n },\n};\n"],"names":["EPS","wrap","x","v","clean","canonicalize","structure","site","toFixedArray","precision","fnv1a","str","hash","i","hashStructure","s","lattice","latticeKey","sitesKey","key","appendSite","insertSite","index","removeSite","_","replaceSite","createMatrix","rows","cols","data","size","buffer","row","col","createLattice","values","cleaned","dot","a","b","sum","norm","angle","u","denom","c","clamped","angles","m","alpha","beta","gamma","inverse3x3","a00","a01","a02","a10","a11","a12","a20","a21","a22","c00","c01","c02","c10","c11","c12","c20","c21","c22","det","invDet","out","inverse","lengths","transpose","matrix","mul","aRows","aCols","bCols","k","metricTensor","AT","RAD2DEG","parameters","TWO_PI","reciprocalLattice","inv","reciprocalLatticeCrystallographic","invT","minor","skipRow","skipCol","ptr","determinant","n","sign","volume","DEG2RAD","fromParameters","alphaR","betaR","gammaR","cosA","cosB","cosG","sinG","v1","v2","cx","cy","czSquared","cz","cubic","hexagonal","monoclinic","orthorhombic","rhombohedral","tetragonal","ready","initMoyo","readFileSync","join","wasmPath","wasmBuffer","init","e","wasmUrl","getSymmetry","tolerance","setting","symbolToId","idToSymbol","counter","positions","numbers","symbol","moyoInput","results","analyze_cell","build","cell","species","sites","pos","supercell","nx","ny","nz","newBasis","y","z","j","createSite","frac","properties","cartesian","result","fractional","cart","vec","distance","dFrac","displaced","dCart","wrapValue","createSpecies","cleanValue","value","tokenize","line","warnUnsupportedSymmetry","spaceGroup","fromCIF","text","lines","atomHeaders","atomRows","inLoop","currentHeaders","collectingAtoms","ix","iy","iz","ispecies","toCIF","p","isSelective","isCartesian","l","fromPOSCAR","cursor","scale","latticeData","symbols","counts","direct","speciesIndex","remaining","totalAtoms","coords","toPOSCAR","options","title","grouped","fromStructureData","kindMap","kind","toStructureData","kinds","findSection","section","idx","fromXSF","vecStart","coordStart","nAtoms","tokens","formatVec","formatLattice","toXSF","latticeLines","parseHeader","comment","info","kvRegex","match","parseLattice","fromXYZ","toXYZ","latticeStr","f","fromOptimade","position","toOptimade","species_at_sites","elements","toJSON","fromJSON","convertMeasurement","from","to","conversions","aliases","resolve","fromUnit","toUnit","convertMeasurementArray","arr","LengthConversions","LengthAliases","LengthUnitSystem","EnergyConversions","EnergyAliases","EnergyUnitSystem","AngleConversions","AngleAliases","AngleUnitSystem"],"mappings":";AAEA,MAAMA,KAAM;AAEZ,SAASC,EAAKC,GAAmB;AAC/B,QAAMC,IAAID,IAAI,KAAK,MAAMA,CAAC;AAC1B,SAAO,KAAK,IAAIC,CAAC,IAAIH,KAAM,IAAIG;AACjC;AAEA,SAASC,EAAMF,GAAmB;AAChC,SAAO,KAAK,IAAIA,CAAC,IAAI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