From b5ab8c9a79e97d0733e1d4ffbef7470666e8fde4 Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Sat, 15 Aug 2026 01:00:07 +0300 Subject: [PATCH 1/6] chore: stop committing dist/, publish WIP builds via CI [release] Mirrors the esse/utils/code rollout: dist/ gitignored, files field added, pre-commit hook no longer force-adds dist, and .github/workflows/release-wip.yml + cleanup-wip-releases.yml wire up mat3ra/actions' composite actions. Bumps @mat3ra/code, @mat3ra/esse, @mat3ra/utils to their WIP release tarballs so this build is tested against the rest of the rollout. @mat3ra/standata is left on its registry pin: made and standata have a circular dependency (standata also depends on made), so this one cross-edge stays untouched rather than trying to bootstrap both at once. RELEASING.md documents the CI-only publish path. --- .github/workflows/cleanup-wip-releases.yml | 36 + .github/workflows/release-wip.yml | 31 + .gitignore | 3 +- .husky/pre-commit | 2 +- RELEASING.md | 69 ++ dist/js/Material.d.ts | 219 ----- dist/js/Material.js | 457 --------- dist/js/basis/basis.d.ts | 207 ----- dist/js/basis/basis.js | 496 ---------- dist/js/basis/constrained_basis.d.ts | 44 - dist/js/basis/constrained_basis.js | 80 -- dist/js/basis/coordinates.d.ts | 22 - dist/js/basis/coordinates.js | 71 -- dist/js/basis/elements.d.ts | 11 - dist/js/basis/elements.js | 21 - dist/js/basis/helpers.d.ts | 11 - dist/js/basis/helpers.js | 18 - dist/js/basis/labels.d.ts | 5 - dist/js/basis/labels.js | 7 - dist/js/cell/cell.d.ts | 32 - dist/js/cell/cell.js | 113 --- dist/js/cell/conventional_cell.d.ts | 6 - dist/js/cell/conventional_cell.js | 80 -- dist/js/cell/primitive_cell.d.ts | 7 - dist/js/cell/primitive_cell.js | 144 --- dist/js/constants.d.ts | 2 - dist/js/constants.js | 25 - dist/js/constants/molecule.d.ts | 16 - dist/js/constants/molecule.js | 19 - dist/js/constraints/constraints.d.ts | 19 - dist/js/constraints/constraints.js | 39 - dist/js/data/reciprocal_paths.json | 111 --- dist/js/generated/MaterialSchemaMixin.d.ts | 5 - dist/js/generated/MaterialSchemaMixin.js | 69 -- dist/js/lattice/lattice.d.ts | 68 -- dist/js/lattice/lattice.js | 278 ------ dist/js/lattice/lattice_types.d.ts | 42 - dist/js/lattice/lattice_types.js | 127 --- .../reciprocal/lattice_reciprocal.d.ts | 88 -- .../lattice/reciprocal/lattice_reciprocal.js | 146 --- dist/js/lattice/reciprocal/paths.d.ts | 9 - dist/js/lattice/reciprocal/paths.js | 29 - .../lattice/reciprocal/symmetry_points.d.ts | 8 - dist/js/lattice/reciprocal/symmetry_points.js | 865 ------------------ dist/js/lattice/unit_cell.d.ts | 30 - dist/js/lattice/unit_cell.js | 31 - dist/js/made.d.ts | 104 --- dist/js/made.js | 90 -- dist/js/parsers/cif.d.ts | 12 - dist/js/parsers/cif.js | 20 - dist/js/parsers/errors.d.ts | 3 - dist/js/parsers/errors.js | 10 - dist/js/parsers/espresso.d.ts | 9 - dist/js/parsers/espresso.js | 23 - dist/js/parsers/native_format_parsers.d.ts | 20 - dist/js/parsers/native_format_parsers.js | 52 -- dist/js/parsers/parsers.d.ts | 27 - dist/js/parsers/parsers.js | 17 - dist/js/parsers/poscar.d.ts | 32 - dist/js/parsers/poscar.js | 184 ---- dist/js/parsers/xyz.d.ts | 45 - dist/js/parsers/xyz.js | 156 ---- dist/js/parsers/xyz_combinatorial_basis.d.ts | 63 -- dist/js/parsers/xyz_combinatorial_basis.js | 248 ----- dist/js/tools/basis.d.ts | 22 - dist/js/tools/basis.js | 105 --- dist/js/tools/cell.d.ts | 10 - dist/js/tools/cell.js | 36 - dist/js/tools/index.d.ts | 23 - dist/js/tools/index.js | 15 - dist/js/tools/material.d.ts | 26 - dist/js/tools/material.js | 53 -- dist/js/tools/supercell.d.ts | 23 - dist/js/tools/supercell.js | 61 -- dist/js/tools/surface.d.ts | 10 - dist/js/tools/surface.js | 159 ---- package-lock.json | 24 +- package.json | 9 +- 78 files changed, 156 insertions(+), 5753 deletions(-) create mode 100644 .github/workflows/cleanup-wip-releases.yml create mode 100644 .github/workflows/release-wip.yml create mode 100644 RELEASING.md delete mode 100644 dist/js/Material.d.ts delete mode 100644 dist/js/Material.js delete mode 100644 dist/js/basis/basis.d.ts delete mode 100644 dist/js/basis/basis.js delete mode 100644 dist/js/basis/constrained_basis.d.ts delete mode 100644 dist/js/basis/constrained_basis.js delete mode 100644 dist/js/basis/coordinates.d.ts delete mode 100644 dist/js/basis/coordinates.js delete mode 100644 dist/js/basis/elements.d.ts delete mode 100644 dist/js/basis/elements.js delete mode 100644 dist/js/basis/helpers.d.ts delete mode 100644 dist/js/basis/helpers.js delete mode 100644 dist/js/basis/labels.d.ts delete mode 100644 dist/js/basis/labels.js delete mode 100644 dist/js/cell/cell.d.ts delete mode 100644 dist/js/cell/cell.js delete mode 100644 dist/js/cell/conventional_cell.d.ts delete mode 100644 dist/js/cell/conventional_cell.js delete mode 100644 dist/js/cell/primitive_cell.d.ts delete mode 100644 dist/js/cell/primitive_cell.js delete mode 100644 dist/js/constants.d.ts delete mode 100644 dist/js/constants.js delete mode 100644 dist/js/constants/molecule.d.ts delete mode 100644 dist/js/constants/molecule.js delete mode 100644 dist/js/constraints/constraints.d.ts delete mode 100644 dist/js/constraints/constraints.js delete mode 100644 dist/js/data/reciprocal_paths.json delete mode 100644 dist/js/generated/MaterialSchemaMixin.d.ts delete mode 100644 dist/js/generated/MaterialSchemaMixin.js delete mode 100644 dist/js/lattice/lattice.d.ts delete mode 100644 dist/js/lattice/lattice.js delete mode 100644 dist/js/lattice/lattice_types.d.ts delete mode 100644 dist/js/lattice/lattice_types.js delete mode 100644 dist/js/lattice/reciprocal/lattice_reciprocal.d.ts delete mode 100644 dist/js/lattice/reciprocal/lattice_reciprocal.js delete mode 100644 dist/js/lattice/reciprocal/paths.d.ts delete mode 100644 dist/js/lattice/reciprocal/paths.js delete mode 100644 dist/js/lattice/reciprocal/symmetry_points.d.ts delete mode 100644 dist/js/lattice/reciprocal/symmetry_points.js delete mode 100644 dist/js/lattice/unit_cell.d.ts delete mode 100644 dist/js/lattice/unit_cell.js delete mode 100644 dist/js/made.d.ts delete mode 100644 dist/js/made.js delete mode 100644 dist/js/parsers/cif.d.ts delete mode 100644 dist/js/parsers/cif.js delete mode 100644 dist/js/parsers/errors.d.ts delete mode 100644 dist/js/parsers/errors.js delete mode 100644 dist/js/parsers/espresso.d.ts delete mode 100644 dist/js/parsers/espresso.js delete mode 100644 dist/js/parsers/native_format_parsers.d.ts delete mode 100644 dist/js/parsers/native_format_parsers.js delete mode 100644 dist/js/parsers/parsers.d.ts delete mode 100644 dist/js/parsers/parsers.js delete mode 100644 dist/js/parsers/poscar.d.ts delete mode 100644 dist/js/parsers/poscar.js delete mode 100644 dist/js/parsers/xyz.d.ts delete mode 100644 dist/js/parsers/xyz.js delete mode 100644 dist/js/parsers/xyz_combinatorial_basis.d.ts delete mode 100644 dist/js/parsers/xyz_combinatorial_basis.js delete mode 100644 dist/js/tools/basis.d.ts delete mode 100644 dist/js/tools/basis.js delete mode 100644 dist/js/tools/cell.d.ts delete mode 100644 dist/js/tools/cell.js delete mode 100644 dist/js/tools/index.d.ts delete mode 100644 dist/js/tools/index.js delete mode 100644 dist/js/tools/material.d.ts delete mode 100644 dist/js/tools/material.js delete mode 100644 dist/js/tools/supercell.d.ts delete mode 100644 dist/js/tools/supercell.js delete mode 100644 dist/js/tools/surface.d.ts delete mode 100644 dist/js/tools/surface.js diff --git a/.github/workflows/cleanup-wip-releases.yml b/.github/workflows/cleanup-wip-releases.yml new file mode 100644 index 000000000..9a69c39b9 --- /dev/null +++ b/.github/workflows/cleanup-wip-releases.yml @@ -0,0 +1,36 @@ +--- + +name: Clean up stale WIP release tarballs + +on: + schedule: + - cron: '0 6 * * 1' # every Monday 06:00 UTC + workflow_dispatch: + inputs: + dry-run: + description: Log keep/delete decisions without deleting anything + type: boolean + default: true + +jobs: + cleanup-wip-releases: + runs-on: ubuntu-latest + steps: + - name: Checkout this repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Checkout actions repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: mat3ra/actions + # TODO: drop `ref` once mat3ra/actions' js/cleanup-wip-releases merges to main + ref: chore/SOF-7942-1 + token: ${{ secrets.BOT_GITHUB_TOKEN }} + path: actions + + - name: Clean up stale WIP releases + uses: ./actions/js/cleanup-wip-releases + with: + # Scheduled runs always delete; workflow_dispatch defaults to dry-run. + dry-run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry-run || 'false' }} + github-token: ${{ secrets.BOT_GITHUB_TOKEN }} diff --git a/.github/workflows/release-wip.yml b/.github/workflows/release-wip.yml new file mode 100644 index 000000000..7da3a0806 --- /dev/null +++ b/.github/workflows/release-wip.yml @@ -0,0 +1,31 @@ +--- + +name: Publish WIP release tarball + +on: push + +jobs: + release-wip: + if: contains(github.event.head_commit.message, '[release]') + runs-on: ubuntu-latest + steps: + - name: Checkout this repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + lfs: true + + - name: Checkout actions repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: mat3ra/actions + # TODO: drop `ref` once mat3ra/actions' js/release-wip merges to main + ref: chore/SOF-7942-1 + token: ${{ secrets.BOT_GITHUB_TOKEN }} + path: actions + + - name: Publish WIP release tarball + uses: ./actions/js/release-wip + with: + package-name: made + build-script: transpile + github-token: ${{ secrets.BOT_GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 9cece4e9e..bf30e96fa 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,7 @@ __pycache__/ *.so # Distribution / packaging -# "dist" folder is not ignored on purpose to be able to install intermediate changes from github commits -# dist +dist/ .Python ./build/ develop-eggs/ diff --git a/.husky/pre-commit b/.husky/pre-commit index e0730e7a8..99187e6f2 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -3,4 +3,4 @@ npx lint-staged --allow-empty npm run transpile -git add dist +# dist/ is gitignored - not staged here diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 000000000..f94bea6e0 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,69 @@ +# Releasing WIP builds for consumers + +`dist/` is build output and is gitignored — it is not committed on any branch. Published +releases (`npm publish`, tagged versions) are unaffected: `npm pack`/`npm publish` build +their file list from the `files` field in `package.json`, not from what's tracked in git. + +To let a consumer (e.g. `web-app`) install a not-yet-mergeable WIP commit without +`github:mat3ra/made#branch` (which has no way to build `dist/` on install), CI publishes +a pre-release tarball asset instead. + +Releases are tagged per **commit**, not per branch: `wip-`. Each commit +gets its own immutable tag/asset URL, so a consumer pinned to a specific commit's tarball +never has the content underneath that URL silently change. + +## Publishing (CI only) + +Include `[release]` anywhere in a commit message and push. `.github/workflows/release-wip.yml` +runs the `js/release-wip` action (from [`mat3ra/actions`](https://github.com/mat3ra/actions)) +on that push, which builds, packs, and publishes the pre-release tarball asset for that +commit. Commits without the marker don't trigger it, so routine pushes stay quiet. + +There is no local/manual equivalent — building and publishing only happens in CI, so the +tarball a consumer installs is always reproducible from a pushed commit, not from +whatever happens to be on someone's machine. + +The download URL follows this shape: + +```text +https://github.com/mat3ra/made/releases/download/wip-/made.tgz +``` + +Re-triggering CI **on the same commit** (e.g. re-running the workflow) re-uploads over +that commit's existing asset (`gh release upload ... --clobber`) rather than minting a +duplicate. A new commit always gets a new tag/URL. + +## Reinstalling in a consumer after a same-commit rebuild + +Because a same-commit rebuild re-uploads over that commit's existing tag/asset, the +download URL doesn't change — which means a plain `npm install` in the consumer won't +pick up the rebuild: npm's cache stores the tarball keyed by URL, and +`package-lock.json` pins the `integrity` hash from the first install, so a +same-URL-but-changed-content refetch either gets served stale from cache or fails with +`EINTEGRITY`. Force a real refetch instead. In `web-app`, use the wrapper script from +repo root: + +```bash +npm run mat3ra:install -- made wip- +``` + +(`web-app/scripts/mat3ra-install.sh` — installs `@mat3ra/made@` with +`--legacy-peer-deps --force`.) + +Delete a pre-release once its commit merges and a real published version supersedes it: + +```bash +gh release delete wip- --yes +``` + +(Or let `cleanup-wip-releases.yml`, below, do it automatically once that commit is no +longer any branch's tip.) + +## Automatic cleanup + +`.github/workflows/cleanup-wip-releases.yml` runs weekly (Monday 06:00 UTC) via the +`js/cleanup-wip-releases` action and deletes any `wip-*` release whose commit is no +longer the tip of any branch. This is branch-aware, not age-based, and never deletes +anything not marked pre-release, regardless of tag. Trigger it manually from the Actions +tab (`workflow_dispatch`, defaults to `dry-run: true`) to test or force an off-schedule +cleanup. diff --git a/dist/js/Material.d.ts b/dist/js/Material.d.ts deleted file mode 100644 index a6f5e56cc..000000000 --- a/dist/js/Material.d.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { InMemoryEntity } from "@mat3ra/code/dist/js/entity"; -import { type Defaultable } from "@mat3ra/code/dist/js/entity/mixins/DefaultableMixin"; -import { type HasMetadata } from "@mat3ra/code/dist/js/entity/mixins/HasMetadataMixin"; -import { type NamedEntity } from "@mat3ra/code/dist/js/entity/mixins/NamedEntityMixin"; -import type { JSONSchema } from "@mat3ra/esse/dist/js/esse/utils"; -import type { AtomicConstraintsSchema, BasisSchema, ConsistencyCheck, DerivedPropertiesSchema, FileSourceSchema, LatticeSchema, MaterialEnhancedHashedSchema, MaterialEnhancedSchema, MaterialHashedSchema, MaterialSchema } from "@mat3ra/esse/dist/js/types"; -import { type BasisConfig } from "./basis/basis"; -import { type ConstrainedBasisConfig, ConstrainedBasis } from "./basis/constrained_basis"; -import { type MaterialSchemaMixin } from "./generated/MaterialSchemaMixin"; -import { Lattice } from "./lattice/lattice"; -export type PartialBy = Omit & Partial>; -/** - * Bundle of material JSON-schema variants used by {@link Material} projections. - * Web-app passes extended schemas here so `toJSON*` return types stay precise. - */ -export type MaterialSchemaMap = { - pure: MaterialSchema; - enhanced: MaterialEnhancedSchema; - hashed: MaterialHashedSchema; - enhancedHashed: MaterialEnhancedHashedSchema; -}; -/** Default ESSE schema map (no web-app extensions). */ -export type DefaultMaterialSchemas = MaterialSchemaMap; -/** - * Constructor config: constraints/hash/metadata optional — normalized in the constructor - * (`parseConstrainedBasis` + {@link Material.updateHash}; `metadata` defaults to `{}`). - */ -export type MaterialConfig = Omit, "basis"> & { - basis: MaterialSchema["basis"] | MaterialEnhancedSchema["basis"]; -}; -export declare const defaultMaterialConfig: MaterialEnhancedSchema; -interface BaseMaterial extends MaterialSchemaMixin, NamedEntity, Defaultable, Required> { -} -declare class BaseMaterial extends InMemoryEntity { -} -/** - * Unified material. Pass extended schemas via {@link MaterialSchemaMap} so each - * `toJSON*` returns the web-app (or other host) schema type. - * - * @example - * ```ts - * type WebappSchemas = { - * pure: MaterialSchema; - * enhanced: WebappMaterialEnhancedSchema; - * hashed: WebappMaterialHashedSchema; - * enhancedHashed: WebappMaterialEnhancedSchema; - * }; - * class CoreMaterial extends Material {} - * ``` - */ -declare class Material extends BaseMaterial { - static createDefault: () => Material; - /** - * Schema used by {@link InMemoryEntity.clean} / {@link toJSON}. - * Defaults to enhanced+hashed; subclasses / web-app Core* may override. - */ - static get jsonSchema(): JSONSchema; - /** Schema for {@link toJSONPure} — override in web-app if the base material schema is extended. */ - static get jsonSchemaPure(): JSONSchema; - /** Schema for {@link toJSONEnhanced}. */ - static get jsonSchemaEnhanced(): JSONSchema; - /** Schema for {@link toJSONHashed}. */ - static get jsonSchemaHashed(): JSONSchema; - /** Schema for {@link toJSONEnhancedHashed}. */ - static get jsonSchemaEnhancedHashed(): JSONSchema; - static get defaultConfig(): MaterialEnhancedSchema; - static constructMaterialFileSource(fileName: string, fileContent: string, fileExtension: string): FileSourceSchema; - /** - * @param config - Partial entity input. `basis.constraints` / `hash` / `metadata` may be omitted; - * constraints and hash are filled here; missing `metadata` becomes `{}`. - * `NoInfer` keeps `Schemas` from being inferred from the config object literal. - */ - constructor(config: NoInfer); - get hash(): Schemas["enhancedHashed"]["hash"]; - set hash(value: Schemas["enhancedHashed"]["hash"]); - get scaledHash(): Schemas["enhancedHashed"]["scaledHash"]; - set scaledHash(value: Schemas["enhancedHashed"]["scaledHash"]); - /** - * Recompute and store {@link hash} from the current basis/lattice (or InChI if non-periodic). - * When non-periodic but InChI is not derived yet (e.g. designer toggle before butler), use - * geometric hash so setters do not throw — same practical UX as main before auto-updateHash. - */ - updateHash(): void; - get basis(): Schemas["enhancedHashed"]["basis"]; - set basis(value: Schemas["enhancedHashed"]["basis"]); - get lattice(): Schemas["enhancedHashed"]["lattice"]; - set lattice(value: Schemas["enhancedHashed"]["lattice"]); - updateFormula(): void; - /** - * @summary Returns the specific derived property (as specified by name) for a material. - */ - getDerivedPropertyByName(name: string): { - name?: "volume"; - units?: "angstrom^3"; - value: number; - } | { - name?: "density"; - units?: "g/cm^3"; - value: number; - } | { - pointGroupSymbol?: string; - spaceGroupSymbol?: string; - tolerance?: { - units?: "angstrom"; - value: number; - }; - name?: "symmetry"; - } | { - name?: "elemental_ratio"; - value: number; - element?: string; - } | { - name?: "p-norm"; - degree?: number; - value: number; - } | { - name?: "inchi"; - value: string; - } | { - name?: "inchi_key"; - value: string; - } | undefined; - /** - * @summary Returns the derived properties array for a material. - */ - getDerivedProperties(): DerivedPropertiesSchema; - unsetFileProps(): void; - setBasis(basis: BasisConfig | ConstrainedBasisConfig): void; - setBasis(basis: string, format: "xyz", units?: BasisSchema["units"]): void; - private setBasisConstraints; - setBasisConstraintsFromArrayOfObjects(constraints: AtomicConstraintsSchema): void; - getBasis(): ConstrainedBasis; - setLattice(lattice: LatticeSchema): void; - getLattice(): Lattice; - /** - * High-level access to unique elements from material instead of basis. - */ - get uniqueElements(): ("H" | "He" | "Li" | "Be" | "B" | "C" | "N" | "O" | "F" | "Ne" | "Na" | "Mg" | "Al" | "Si" | "P" | "S" | "Cl" | "Ar" | "K" | "Ca" | "Sc" | "Ti" | "V" | "Cr" | "Mn" | "Fe" | "Co" | "Ni" | "Cu" | "Zn" | "Ga" | "Ge" | "As" | "Se" | "Br" | "Kr" | "Rb" | "Sr" | "Y" | "Zr" | "Nb" | "Mo" | "Tc" | "Ru" | "Rh" | "Pd" | "Ag" | "Cd" | "In" | "Sn" | "Sb" | "Te" | "I" | "Xe" | "Cs" | "Ba" | "La" | "Ce" | "Pr" | "Nd" | "Pm" | "Sm" | "Eu" | "Gd" | "Tb" | "Dy" | "Ho" | "Er" | "Tm" | "Yb" | "Lu" | "Hf" | "Ta" | "W" | "Re" | "Os" | "Ir" | "Pt" | "Au" | "Hg" | "Tl" | "Pb" | "Bi" | "Po" | "At" | "Rn" | "Fr" | "Ra" | "Ac" | "Th" | "Pa" | "U" | "Np" | "Pu" | "Am" | "Cm" | "Bk" | "Cf" | "Es" | "Fm" | "Md" | "No" | "Lr" | "Rf" | "Db" | "Sg" | "Bh" | "Hs" | "Mt" | "Ds" | "Rg" | "Cn" | "Nh" | "Fl" | "Mc" | "Lv" | "Ts" | "Og" | "X" | "Vac")[]; - /** - * Returns the inchi string from the derivedProperties for a non-periodic material, or throws an error if the - * inchi cannot be found. - * @returns {String} - */ - getInchiStringForHash(): string; - /** - * Calculates hash from basis and lattice. Algorithm expects the following: - * - asserts lattice units to be angstrom - * - asserts basis units to be crystal - * - asserts basis coordinates and lattice measurements are rounded to hash precision - * - forms strings for lattice and basis - * - creates MD5 hash from basisStr + latticeStr + salt - * @param salt Salt for hashing, empty string by default. - * @param isScaled Whether to scale the lattice parameter 'a' to 1. - */ - calculateHash(salt?: string, isScaled?: boolean, bypassNonPeriodicCheck?: boolean): string; - /** - * Converts basis to crystal/fractional coordinates. - */ - toCrystal(): void; - /** - * Converts current material's basis coordinates to cartesian. - * No changes if coordinates already cartesian. - */ - toCartesian(): void; - /** - * Returns material's basis in XYZ format (includes atomic constraints when present). - */ - getBasisAsXyz(fractional?: boolean): string; - /** - * Returns material in Quantum Espresso output format: - * ``` - * CELL_PARAMETERS (angstroms) - * -0.543131284 -0.000000000 0.543131284 - * -0.000000000 0.543131284 0.543131284 - * -0.543131284 0.543131284 0.000000000 - * - * ATOMIC_POSITIONS (crystal) - * Si 0.000000000 0.000000000 -0.000000000 - * Si 0.250000000 0.250000000 0.250000000 - * ``` - */ - getAsQEFormat(): string; - /** - * Returns material in POSCAR format. Pass `true` to ignore original poscar source and re-serialize. - */ - getAsPOSCAR(ignoreOriginal?: boolean, omitConstraints?: boolean): string; - /** - * Returns a copy of the material with conventional cell constructed instead of primitive. - */ - getACopyWithConventionalCell(): this; - /** - * @summary a series of checks for the material and returns an array of results in ConsistencyChecks format. - * @returns Array of checks results - */ - getConsistencyChecks(): ConsistencyCheck[]; - /** - * @summary a series of checks for the material's basis and returns an array of results in ConsistencyChecks format. - * @returns Array of checks results - */ - getBasisConsistencyChecks(): ConsistencyCheck[]; - /** - * Full material JSON: constrained basis + hash fields from live getters. - * Variants below AJV-clean this payload against the matching ESSE schema. - * Builds from `_json` (not `super.toJSON`) so we do not pre-clean against - * {@link Material.jsonSchema} before projecting to a narrower schema. - */ - private getFullJSON; - /** - * Clone {@link getFullJSON} and validate/clean against `jsonSchema` via AJV - * (same path as {@link InMemoryEntity.validateData} / {@link InMemoryEntity.clean}). - */ - private cleanFullJSONAgainstSchema; - toJSONPure(): Schemas["pure"]; - toJSONEnhanced(): Schemas["enhanced"]; - toJSONHashed(): Schemas["hashed"]; - toJSONEnhancedHashed(): Schemas["enhancedHashed"]; - toJSON(): Schemas["enhancedHashed"]; -} -export default Material; diff --git a/dist/js/Material.js b/dist/js/Material.js deleted file mode 100644 index b431b2677..000000000 --- a/dist/js/Material.js +++ /dev/null @@ -1,457 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultMaterialConfig = void 0; -const entity_1 = require("@mat3ra/code/dist/js/entity"); -const in_memory_1 = require("@mat3ra/code/dist/js/entity/in_memory"); -const DefaultableMixin_1 = require("@mat3ra/code/dist/js/entity/mixins/DefaultableMixin"); -const HasMetadataMixin_1 = require("@mat3ra/code/dist/js/entity/mixins/HasMetadataMixin"); -const NamedEntityMixin_1 = require("@mat3ra/code/dist/js/entity/mixins/NamedEntityMixin"); -const clone_1 = require("@mat3ra/code/dist/js/utils/clone"); -const JSONSchemasInterface_1 = __importDefault(require("@mat3ra/esse/dist/js/esse/JSONSchemasInterface")); -const crypto_js_1 = __importDefault(require("crypto-js")); -const constrained_basis_1 = require("./basis/constrained_basis"); -const conventional_cell_1 = require("./cell/conventional_cell"); -const constraints_1 = require("./constraints/constraints"); -const MaterialSchemaMixin_1 = require("./generated/MaterialSchemaMixin"); -const lattice_1 = require("./lattice/lattice"); -const parsers_1 = __importDefault(require("./parsers/parsers")); -const supercell_1 = __importDefault(require("./tools/supercell")); -/** ESSE `$id` values for material schema variants. */ -const MATERIAL_SCHEMA_IDS = { - pure: "material", - enhanced: "material-enhanced", - hashed: "material-hashed", - enhancedHashed: "material-enhanced-hashed", -}; -function parseConstrainedBasis(textOrObject, format, units) { - if (typeof textOrObject === "string") { - if (format !== "xyz") { - throw new Error("Invalid format"); - } - return parsers_1.default.xyz.toBasisConfig(textOrObject, units); - } - if ("constraints" in textOrObject) { - return textOrObject; - } - return { ...textOrObject, constraints: [] }; -} -exports.defaultMaterialConfig = { - name: "Silicon FCC", - basis: { - elements: [ - { - id: 0, - value: "Si", - }, - { - id: 1, - value: "Si", - }, - ], - coordinates: [ - { - id: 0, - value: [0.0, 0.0, 0.0], - }, - { - id: 1, - value: [0.25, 0.25, 0.25], - }, - ], - units: "crystal", - constraints: [], - }, - lattice: { - // Primitive cell for Diamond FCC Silicon at ambient conditions - type: "FCC", - a: 3.867, - b: 3.867, - c: 3.867, - alpha: 60, - beta: 60, - gamma: 60, - units: { - length: "angstrom", - angle: "degree", - }, - }, - metadata: {}, -}; -class BaseMaterial extends entity_1.InMemoryEntity { -} -(0, MaterialSchemaMixin_1.materialSchemaMixin)(BaseMaterial.prototype); -(0, NamedEntityMixin_1.namedEntityMixin)(BaseMaterial.prototype); -(0, DefaultableMixin_1.defaultableEntityMixin)(BaseMaterial); -(0, HasMetadataMixin_1.hasMetadataMixin)(BaseMaterial.prototype); -/** - * Unified material. Pass extended schemas via {@link MaterialSchemaMap} so each - * `toJSON*` returns the web-app (or other host) schema type. - * - * @example - * ```ts - * type WebappSchemas = { - * pure: MaterialSchema; - * enhanced: WebappMaterialEnhancedSchema; - * hashed: WebappMaterialHashedSchema; - * enhancedHashed: WebappMaterialEnhancedSchema; - * }; - * class CoreMaterial extends Material {} - * ``` - */ -class Material extends BaseMaterial { - /** - * Schema used by {@link InMemoryEntity.clean} / {@link toJSON}. - * Defaults to enhanced+hashed; subclasses / web-app Core* may override. - */ - static get jsonSchema() { - return this.jsonSchemaEnhancedHashed; - } - /** Schema for {@link toJSONPure} — override in web-app if the base material schema is extended. */ - static get jsonSchemaPure() { - return JSONSchemasInterface_1.default.getRequiredSchemaById(MATERIAL_SCHEMA_IDS.pure); - } - /** Schema for {@link toJSONEnhanced}. */ - static get jsonSchemaEnhanced() { - return JSONSchemasInterface_1.default.getRequiredSchemaById(MATERIAL_SCHEMA_IDS.enhanced); - } - /** Schema for {@link toJSONHashed}. */ - static get jsonSchemaHashed() { - return JSONSchemasInterface_1.default.getRequiredSchemaById(MATERIAL_SCHEMA_IDS.hashed); - } - /** Schema for {@link toJSONEnhancedHashed}. */ - static get jsonSchemaEnhancedHashed() { - return JSONSchemasInterface_1.default.getRequiredSchemaById(MATERIAL_SCHEMA_IDS.enhancedHashed); - } - static get defaultConfig() { - return exports.defaultMaterialConfig; - } - static constructMaterialFileSource(fileName, fileContent, fileExtension) { - return { - extension: fileExtension, - filename: fileName, - text: fileContent, - hash: crypto_js_1.default.MD5(fileContent).toString(), - }; - } - /** - * @param config - Partial entity input. `basis.constraints` / `hash` / `metadata` may be omitted; - * constraints and hash are filled here; missing `metadata` becomes `{}`. - * `NoInfer` keeps `Schemas` from being inferred from the config object literal. - */ - constructor(config) { - var _a, _b, _c, _d; - const basis = parseConstrainedBasis(config.basis); - super({ - ...config, - basis, - name: (_b = (_a = config.name) !== null && _a !== void 0 ? _a : config.formula) !== null && _b !== void 0 ? _b : "", - metadata: (_c = config.metadata) !== null && _c !== void 0 ? _c : {}, - hash: (_d = config.hash) !== null && _d !== void 0 ? _d : "", - }); - this.formula = config.formula || this.getBasis().formula; - this.name = this.name || this.formula; - this.updateHash(); - } - get hash() { - return this.requiredProp("hash"); - } - set hash(value) { - this.setProp("hash", value); - } - get scaledHash() { - return this.prop("scaledHash"); - } - set scaledHash(value) { - this.setProp("scaledHash", value); - } - /** - * Recompute and store {@link hash} from the current basis/lattice (or InChI if non-periodic). - * When non-periodic but InChI is not derived yet (e.g. designer toggle before butler), use - * geometric hash so setters do not throw — same practical UX as main before auto-updateHash. - */ - updateHash() { - const hasInchi = Boolean(this.getDerivedPropertyByName("inchi")); - this.hash = - this.isNonPeriodic && !hasInchi - ? this.calculateHash("", false, true) - : this.calculateHash(); - } - // Override schema-mixin accessors so basis/lattice changes keep hash in sync. - get basis() { - return this.requiredProp("basis"); - } - set basis(value) { - this.setProp("basis", value); - this.updateHash(); - } - get lattice() { - return this.requiredProp("lattice"); - } - set lattice(value) { - this.setProp("lattice", value); - this.updateHash(); - } - updateFormula() { - const basis = this.getBasis(); - this.formula = basis.formula; - this.unitCellFormula = basis.unitCellFormula; - } - /** - * @summary Returns the specific derived property (as specified by name) for a material. - */ - getDerivedPropertyByName(name) { - return this.getDerivedProperties().find((x) => x.name === name); - } - /** - * @summary Returns the derived properties array for a material. - */ - getDerivedProperties() { - var _a; - return (_a = this.derivedProperties) !== null && _a !== void 0 ? _a : []; - } - unsetFileProps() { - this.unsetProp("src"); - this.unsetProp("icsdId"); - this.unsetProp("external"); - } - setBasis(textOrObject, format, units) { - this.basis = parseConstrainedBasis(textOrObject, format, units); - this.unsetFileProps(); - this.updateFormula(); - } - setBasisConstraints(constraints) { - this.setBasis({ - ...this.basis, - constraints: constraints.map((constraint) => ({ - id: constraint.id, - value: constraint.value, - })), - }); - } - setBasisConstraintsFromArrayOfObjects(constraints) { - this.setBasisConstraints(constraints.map((constraint) => constraints_1.Constraint.fromValueAndId(constraint.value, constraint.id))); - } - getBasis() { - return new constrained_basis_1.ConstrainedBasis({ - ...parseConstrainedBasis(this.basis), - cell: this.getLattice().vectors, - }); - } - setLattice(lattice) { - const basis = this.getBasis(); - const originalIsInCrystalUnits = basis.isInCrystalUnits; - basis.toCartesian(); - basis.cell = new lattice_1.Lattice(lattice).vectors; - if (originalIsInCrystalUnits) { - basis.toCrystal(); - } - this.basis = basis.toJSON(); - this.lattice = lattice; - this.unsetFileProps(); - } - getLattice() { - return new lattice_1.Lattice(this.lattice); - } - /** - * High-level access to unique elements from material instead of basis. - */ - get uniqueElements() { - return this.getBasis().uniqueElements; - } - /** - * Returns the inchi string from the derivedProperties for a non-periodic material, or throws an error if the - * inchi cannot be found. - * @returns {String} - */ - getInchiStringForHash() { - const inchi = this.getDerivedPropertyByName("inchi"); - if (inchi) { - return inchi.value; - } - throw new Error("Hash cannot be created. Missing InChI string in derivedProperties"); - } - /** - * Calculates hash from basis and lattice. Algorithm expects the following: - * - asserts lattice units to be angstrom - * - asserts basis units to be crystal - * - asserts basis coordinates and lattice measurements are rounded to hash precision - * - forms strings for lattice and basis - * - creates MD5 hash from basisStr + latticeStr + salt - * @param salt Salt for hashing, empty string by default. - * @param isScaled Whether to scale the lattice parameter 'a' to 1. - */ - calculateHash(salt = "", isScaled = false, bypassNonPeriodicCheck = false) { - let message; - if (!this.isNonPeriodic || bypassNonPeriodicCheck) { - message = - this.getBasis().hashString + - "#" + - this.getLattice().getHashString(isScaled) + - "#" + - salt; - } - else { - message = this.getInchiStringForHash(); - } - return crypto_js_1.default.MD5(message).toString(); - } - /** - * Converts basis to crystal/fractional coordinates. - */ - toCrystal() { - this.setBasis(this.getBasis().toCrystal().toJSON()); - } - /** - * Converts current material's basis coordinates to cartesian. - * No changes if coordinates already cartesian. - */ - toCartesian() { - this.setBasis(this.getBasis().toCartesian().toJSON()); - } - /** - * Returns material's basis in XYZ format (includes atomic constraints when present). - */ - getBasisAsXyz(fractional = false) { - return parsers_1.default.xyz.fromMaterial(this.toJSONEnhanced(), fractional); - } - /** - * Returns material in Quantum Espresso output format: - * ``` - * CELL_PARAMETERS (angstroms) - * -0.543131284 -0.000000000 0.543131284 - * -0.000000000 0.543131284 0.543131284 - * -0.543131284 0.543131284 0.000000000 - * - * ATOMIC_POSITIONS (crystal) - * Si 0.000000000 0.000000000 -0.000000000 - * Si 0.250000000 0.250000000 0.250000000 - * ``` - */ - getAsQEFormat() { - return parsers_1.default.espresso.toEspressoFormat(this.toJSONPure()); - } - /** - * Returns material in POSCAR format. Pass `true` to ignore original poscar source and re-serialize. - */ - getAsPOSCAR(ignoreOriginal = false, omitConstraints = false) { - var _a; - // By default return original source if exists - if (((_a = this.src) === null || _a === void 0 ? void 0 : _a.extension) === "poscar" && !ignoreOriginal) { - return this.src.text; - } - return parsers_1.default.poscar.toPoscar(this.toJSONEnhanced(), omitConstraints); - } - /** - * Returns a copy of the material with conventional cell constructed instead of primitive. - */ - getACopyWithConventionalCell() { - const material = this.clone(); - const lattice = this.getLattice(); - // if conventional and primitive cells are the same => return a copy. - if ((0, conventional_cell_1.isConventionalCellSameAsPrimitiveForLatticeType)(lattice.type)) { - return material; - } - const conventionalSupercellMatrix = conventional_cell_1.PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIERS[lattice.type]; - const conventionalLatticeType = conventional_cell_1.PRIMITIVE_TO_CONVENTIONAL_CELL_LATTICE_TYPES[lattice.type]; - const config = supercell_1.default.generateConfig(this, conventionalSupercellMatrix); - config.lattice.type = conventionalLatticeType; - config.name = `${this.name} - conventional cell`; - return this.clone(config); - } - /** - * @summary a series of checks for the material and returns an array of results in ConsistencyChecks format. - * @returns Array of checks results - */ - getConsistencyChecks() { - const basisChecks = this.getBasisConsistencyChecks(); - // any other Material checks can be added here - return basisChecks; - } - /** - * @summary a series of checks for the material's basis and returns an array of results in ConsistencyChecks format. - * @returns Array of checks results - */ - getBasisConsistencyChecks() { - const checks = []; - const limit = 1000; - const basis = this.getBasis(); - if (basis.elements.length < limit) { - const overlappingAtomsGroups = basis.getOverlappingAtoms(); - overlappingAtomsGroups.forEach(({ id1, id2, element1, element2 }) => { - checks.push({ - key: `basis.coordinates.${id1}`, - name: "atomsOverlap", - severity: "warning", - message: `Atom ${element1} is too close to ${element2} at position ${id2 + 1}`, - }, { - key: `basis.coordinates.${id2}`, - name: "atomsOverlap", - severity: "warning", - message: `Atom ${element2} is too close to ${element1} at position ${id1 + 1}`, - }); - }); - } - return checks; - } - /** - * Full material JSON: constrained basis + hash fields from live getters. - * Variants below AJV-clean this payload against the matching ESSE schema. - * Builds from `_json` (not `super.toJSON`) so we do not pre-clean against - * {@link Material.jsonSchema} before projecting to a narrower schema. - */ - getFullJSON() { - const fullJSON = { - ...(0, clone_1.clone)(this._json), - lattice: this.getLattice().toJSON(), - basis: this.getBasis().toJSON(), - isNonPeriodic: this.isNonPeriodic, - hash: this.hash, - }; - if (this.scaledHash !== undefined) { - fullJSON.scaledHash = this.scaledHash; - } - return fullJSON; - } - /** - * Clone {@link getFullJSON} and validate/clean against `jsonSchema` via AJV - * (same path as {@link InMemoryEntity.validateData} / {@link InMemoryEntity.clean}). - */ - cleanFullJSONAgainstSchema(jsonSchema) { - var _a, _b, _c; - try { - return this.constructor.validateData((0, clone_1.deepClone)(this.getFullJSON()), true, jsonSchema); - } - catch (err) { - // validateData throws EntityError with only the code as message — log details for DevTools. - if (err instanceof in_memory_1.EntityError) { - console.error("Material.toJSON validation failed", { - code: err.code, - error: (_a = err.details) === null || _a === void 0 ? void 0 : _a.error, - json: (_b = err.details) === null || _b === void 0 ? void 0 : _b.json, - schema: (_c = err.details) === null || _c === void 0 ? void 0 : _c.schema, - }); - } - throw err; - } - } - toJSONPure() { - return this.cleanFullJSONAgainstSchema(this.constructor.jsonSchemaPure); - } - toJSONEnhanced() { - return this.cleanFullJSONAgainstSchema(this.constructor.jsonSchemaEnhanced); - } - toJSONHashed() { - return this.cleanFullJSONAgainstSchema(this.constructor.jsonSchemaHashed); - } - toJSONEnhancedHashed() { - return this.cleanFullJSONAgainstSchema(this.constructor.jsonSchemaEnhancedHashed); - } - toJSON() { - // Same payload as toJSONEnhancedHashed when jsonSchema is the enhanced-hashed default. - return this.cleanFullJSONAgainstSchema(this.constructor.jsonSchema); - } -} -exports.default = Material; diff --git a/dist/js/basis/basis.d.ts b/dist/js/basis/basis.d.ts deleted file mode 100644 index a670dd4fd..000000000 --- a/dist/js/basis/basis.d.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { InMemoryEntity } from "@mat3ra/code/dist/js/entity"; -import { BaseInMemoryEntitySchema, BasisSchema, Coordinate3DSchema, Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -import { Cell } from "../cell/cell"; -import { AtomicCoordinateValue, Coordinates } from "./coordinates"; -import { AtomicElementValue, Elements } from "./elements"; -import { AtomicLabelValue, Labels } from "./labels"; -export interface ElementWithCoordinate { - id?: number; - element: AtomicElementValue; - coordinate: AtomicCoordinateValue; -} -export interface ElementCount { - count: number; - value: AtomicElementValue; -} -interface Overlap { - id1: number; - id2: number; - element1: AtomicElementValue; - element2: AtomicElementValue; -} -export interface BasisConfig extends BasisSchema { - cell?: Cell; - isEmpty?: boolean; -} -export interface ElementsAndCoordinatesConfig { - elements: AtomicElementValue[]; - coordinates: AtomicCoordinateValue[]; - labels?: AtomicLabelValue[]; - units?: BasisSchema["units"]; - cell?: Cell; -} -type BasisEntitySchema = S & BaseInMemoryEntitySchema; -export declare class Basis extends InMemoryEntity> implements BasisSchema { - static defaultConfig: BasisSchema; - units: BasisSchema["units"]; - cell: Cell; - _elements: Elements; - _coordinates: Coordinates; - _labels: Labels; - static _convertValuesToConfig({ elements, coordinates, units, cell, labels, }: ElementsAndCoordinatesConfig): BasisConfig; - static fromElementsAndCoordinates({ elements, coordinates, units, cell, labels, }: ElementsAndCoordinatesConfig): Basis; - constructor(config?: NoInfer); - get elements(): BasisSchema["elements"]; - set elements(elements: BasisSchema["elements"]); - get coordinates(): BasisSchema["coordinates"]; - set coordinates(coordinates: BasisSchema["coordinates"]); - get labels(): BasisSchema["labels"]; - set labels(labels: BasisSchema["labels"]); - toJSON(exclude?: (keyof BasisEntitySchema)[]): BasisEntitySchema; - clone(): this; - removeAllAtoms(): void; - get cellRounded(): import("@mat3ra/esse/dist/js/types").Matrix3X3Schema; - get elementsArray(): object[]; - getElementsAsObject(): BasisSchema["elements"]; - get coordinatesAsArray(): Coordinate3DSchema[]; - get isInCartesianUnits(): boolean; - get isInCrystalUnits(): boolean; - toCartesian(): this; - toCrystal(): this; - getElementByIndex(idx: number): AtomicElementValue; - getElementById(id: number): AtomicElementValue; - getCoordinateValueByIndex(idx: number): AtomicCoordinateValue; - getCoordinateValueById(id: number): AtomicCoordinateValue; - toStandardRepresentation(): void; - /** A representation where all coordinates are within 0 and 1 in crystal units */ - get standardRepresentation(): BasisSchema; - /** - * Add atom with a chemical element at coordinate. - */ - addAtom({ element, coordinate }: ElementWithCoordinate): void; - /** - * Remove atom with a chemical element at coordinate either by passing the (element AND coordinate) OR id. - */ - removeAtom({ element, coordinate, id }: ElementWithCoordinate): void; - /** - * Unique names (symbols) of the chemical elements basis. E.g. `['Si', 'Li']` - */ - get uniqueElements(): AtomicElementValue[]; - /** - * Returns unique chemical elements with their count sorted by electronegativity. - * `{ "Fe": 4.0, "O": 8.0, "Li": 2.0}`. - */ - get uniqueElementCountsSortedByElectronegativity(): import("lodash").Dictionary; - /** - * Returns chemical elements with their count wrt their original order in the basis. - * Note: entries for the same element separated by another element are considered separately. - * [{"count":1, "value":"Zr"}, {"count":23, "value":"H"}, {"count":11, "value":"Zr"}, {"count":1, "value":"H"}] - */ - get elementCounts(): ElementCount[]; - /** - * Reduced formula in IUPAC format. E.g., Na2SO4 - */ - get formula(): string; - /** - * Returns the unit cell formula as object `{ "Fe": 4.0, "O": 8.0, "Li": 2.0}` - */ - get unitCellFormula(): string; - /** - * Returns a nested array with elements and their corresponding coordinates - * @example Output: [ ["Si", [0,0,0]], ["Si", [0.5,0.5,0.5]] ] - */ - get elementsAndCoordinatesArray(): [AtomicElementValue, AtomicCoordinateValue][]; - /** - * Returns a nested array with elements and their corresponding coordinates with labels - * @example Output: [ ["Si", [0,0,0], ['1']], ["Si", [0.5,0.5,0.5]] , ['2']] - */ - get elementsAndCoordinatesAndLabelsArray(): [ - AtomicElementValue, - AtomicCoordinateValue, - AtomicLabelValue - ][]; - /** - * @summary Concatenates elements and sorts them in alphanumeric order. - * E.g., - * ``` - * elements: [{id: 0, value: 'Si'}, {id: 1, value: 'Si'}] - * coordinates: [{id: 0, value: [1,0,0]}, {id: 1, value: [0, 1, 0]}] - * - * result: "Si 0,1,0;Si 1,0,0" - * ``` - * This guarantees the independence from the order in the elements array. - */ - getAsSortedString(): string; - /** - * Returns a string for hash calculation (in crystal units) - */ - get hashString(): string; - get atomicLabelsArray(): string[]; - get elementsWithLabelsArray(): string[]; - /** - * Returns an array of strings with chemical elements and their atomic positions. - * E.g., ``` ['Si 0 0 0', 'Li 0.5 0.5 0.5']``` - */ - get atomicPositions(): string[]; - /** - * @summary Returns number of atoms in material - */ - get nAtoms(): number; - /** - * @summary Returns true if bases are equal, otherwise - false. - * @param anotherBasisClsInstance {Basis} Another Basis. - */ - isEqualTo(anotherBasisClsInstance: { - hashString: string; - }): boolean; - /** - * @summary Returns true if basis cells are equal, otherwise - false. - * @param anotherBasisClsInstance {Basis} Another Basis. - */ - hasEquivalentCellTo(anotherBasisClsInstance: { - cell: Cell; - }): boolean; - /** - * @summary Returns the minimum cubic lattice size for a non-periodic structure. - * Single-atom structures use the element atomic radius floored at defaultMinimumLatticeSize. - * Multi-atom structures scale the maximum pairwise distance by 3 when W=min/max pairwise distance - * is ~1 (diatomic), otherwise by 2. - */ - getMinimumLatticeSize(defaultMinimumLatticeSize?: number): number; - /** - * @summary function returns an array of overlapping atoms within specified tolerance. - */ - getOverlappingAtoms(): Overlap[]; - /** - * @summary function returns the max distance between pairs of basis coordinates by - * calculating the distance between pairs of basis coordinates. - * basis coordinates = [[x1, y1, z1], [x2, y2, z2], ... [xn, yn, zn]] - * n = last set of coordinates - * n-1 = second to last set of coordinates - * - * Iterate through pairs without redundancy. - * pair 0,1 pair 0,2 pair 0,3 ... pair 0,n - * - pair 1,2 pair 1,3 ... pair 1,n - * - - - pair 2,3 ... pair 2,n - * - - - ... ... - * - - - ... ... pair n-1, n - * - */ - get maxPairwiseDistance(): number; - get minPairwiseDistance(): number; - getPairwiseDistanceExtremum(extremum: "max" | "min"): number; - /** - * @summary Function takes basis coordinates and transposes them so that the values for each dimension of the - * the basis are in their own nested array. - * Then the center point for each dimension of the coordinates is calculated. - * - * initial basisCoordinates - * [[x1, y1, z1], - * [x2, y2, z2], - * [.., .., ..], - * [xn, yn, zn]] - * - * transposed basisCoordinates - * [[x1, x2, ...xn], - * [y1, y2, ...yn], - * [z1, z2, ...zn]] - * - * Returns an array = [xCenter, yCenter, zCenter] - */ - get centerOfCoordinatesPoint(): AtomicCoordinateValue; - /** - * @summary Function translates coordinates by the vector passed as an argument. - */ - translateByVector(translationVector: Vector3DSchema): void; -} -export {}; diff --git a/dist/js/basis/basis.js b/dist/js/basis/basis.js deleted file mode 100644 index 1b3e8949e..000000000 --- a/dist/js/basis/basis.js +++ /dev/null @@ -1,496 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Basis = void 0; -// @ts-ignore -const periodic_table_js_1 = require("@exabyte-io/periodic-table.js"); -const entity_1 = require("@mat3ra/code/dist/js/entity"); -const utils_1 = require("@mat3ra/utils"); -const lodash_1 = require("lodash"); -const cell_1 = require("../cell/cell"); -const constants_1 = require("../constants"); -const lattice_1 = require("../lattice/lattice"); -const coordinates_1 = require("./coordinates"); -const elements_1 = require("./elements"); -const labels_1 = require("./labels"); -const DEFAULT_BASIS_CONFIG = { - elements: [ - { - id: 0, - value: "Si", - }, - { - id: 1, - value: "Si", - }, - ], - coordinates: [ - { - id: 0, - value: [0, 0, 0], - }, - { - id: 1, - value: [0.25, 0.25, 0.25], - }, - ], - units: "crystal", -}; -// Keep `{` on same line as `implements` to satisfy brace-style (conflicts with Prettier multi-line heritage). -// prettier-ignore -class Basis extends entity_1.InMemoryEntity { - static _convertValuesToConfig({ elements = [], coordinates = [], units = constants_1.ATOMIC_COORD_UNITS.crystal, cell = new cell_1.Cell(), labels = [], }) { - const elementsArrayWithIdsJSON = elements_1.Elements.fromValues(elements).toJSON(); - const coordinatesArrayWithIdsJSON = coordinates_1.Coordinates.fromValues(coordinates).toJSON(); - const labelsArrayWithIdsJSON = labels_1.Labels.fromValues(labels).toJSON(); - return { - elements: elementsArrayWithIdsJSON, - coordinates: coordinatesArrayWithIdsJSON, - units, - cell, - labels: labelsArrayWithIdsJSON, - }; - } - static fromElementsAndCoordinates({ elements = [], coordinates = [], units = constants_1.ATOMIC_COORD_UNITS.crystal, cell = new cell_1.Cell(), labels = [], }) { - return new Basis(Basis._convertValuesToConfig({ - elements, - coordinates, - units, - cell, - labels, - })); - } - // NoInfer: keep default S (or an explicit type arg) instead of inferring S from the config literal. - constructor(config = Basis.defaultConfig) { - super(config); - const { elements, coordinates, units, labels } = config; - this.cell = new cell_1.Cell(config.cell); - this.units = units || constants_1.ATOMIC_COORD_UNITS.crystal; - this._elements = elements_1.Elements.fromObjects(elements); - this._coordinates = coordinates_1.Coordinates.fromObjects(coordinates); - this._labels = labels_1.Labels.fromObjects(labels || []); - } - get elements() { - return this._elements.toJSON(); - } - set elements(elements) { - this._elements = elements_1.Elements.fromObjects(elements); - } - get coordinates() { - return this._coordinates.toJSON(); - } - set coordinates(coordinates) { - this._coordinates = coordinates_1.Coordinates.fromObjects(coordinates); - } - get labels() { - return this._labels.toJSON(); - } - set labels(labels) { - this._labels = labels_1.Labels.fromObjects(labels || []); - } - toJSON(exclude = ["cell"]) { - var _a; - return { - ...super.toJSON(exclude), - elements: this.elements, - coordinates: this.coordinates, - units: this.units, - ...(((_a = this.labels) === null || _a === void 0 ? void 0 : _a.length) ? { labels: this.labels } : {}), - }; - } - clone() { - const instance = super.clone(); - instance.cell = this.cell.clone(); - return instance; - } - removeAllAtoms() { - this.elements = []; - this.coordinates = []; - this.labels = []; - } - get cellRounded() { - return this.cell.vectorArraysRounded; - } - get elementsArray() { - return this._elements.toJSON(); - } - getElementsAsObject() { - return this.elements; - } - get coordinatesAsArray() { - return this._coordinates.values; - } - get isInCartesianUnits() { - return this.units === constants_1.ATOMIC_COORD_UNITS.cartesian; - } - get isInCrystalUnits() { - return this.units === constants_1.ATOMIC_COORD_UNITS.crystal; - } - toCartesian() { - if (this.isInCartesianUnits) - return this; - this._coordinates.mapArrayInPlace((point) => this.cell.convertPointToCartesian(point)); - this.units = constants_1.ATOMIC_COORD_UNITS.cartesian; - return this; - } - toCrystal() { - if (this.isInCrystalUnits) - return this; - this._coordinates.mapArrayInPlace((point) => this.cell.convertPointToCrystal(point)); - this.units = constants_1.ATOMIC_COORD_UNITS.crystal; - return this; - } - getElementByIndex(idx) { - return this._elements.getElementValueByIndex(idx); - } - getElementById(id) { - const result = this._elements.getElementValueById(id); - if (result) { - return result; - } - throw new Error(`Element with index ${id} not found`); - } - getCoordinateValueByIndex(idx) { - const value = this._coordinates.getElementValueByIndex(idx); - if (value) { - return value; - } - throw new Error(`Coordinate with index ${idx} not found`); - } - getCoordinateValueById(id) { - const coordinate = this._coordinates.getElementValueById(id); - if (coordinate) { - return coordinate; - } - throw new Error(`Coordinate with index ${id} not found`); - } - toStandardRepresentation() { - this.toCrystal(); - this._coordinates.mapArrayInPlace((point) => point.map((x) => utils_1.Utils.math.mod(x))); - } - /** A representation where all coordinates are within 0 and 1 in crystal units */ - get standardRepresentation() { - const originalIsInCartesianUnits = this.isInCartesianUnits; - this.toStandardRepresentation(); - const result = this.toJSON(); - if (originalIsInCartesianUnits) - this.toCartesian(); - return result; - } - /** - * Add atom with a chemical element at coordinate. - */ - addAtom({ element = "Si", coordinate = [0.5, 0.5, 0.5] }) { - this._elements.addItem(element); - this._coordinates.addItem(coordinate); - this.coordinates = this._coordinates.toJSON(); - } - /** - * Remove atom with a chemical element at coordinate either by passing the (element AND coordinate) OR id. - */ - removeAtom({ element, coordinate, id }) { - if (element && coordinate) { - const coordinateId = this._coordinates.getElementIdByValue(coordinate) || -1; - this._elements.removeItem(coordinateId, id); - this._coordinates.removeItem(coordinateId, id); - } - } - /** - * Unique names (symbols) of the chemical elements basis. E.g. `['Si', 'Li']` - */ - get uniqueElements() { - return (0, lodash_1.uniq)(this._elements.values); - } - /** - * Returns unique chemical elements with their count sorted by electronegativity. - * `{ "Fe": 4.0, "O": 8.0, "Li": 2.0}`. - */ - get uniqueElementCountsSortedByElectronegativity() { - return (0, lodash_1.chain)(this.elements) - .sortBy("value") - .sortBy((x) => (0, periodic_table_js_1.getElectronegativity)(x.value)) - .countBy((element) => element.value) - .value(); - } - /** - * Returns chemical elements with their count wrt their original order in the basis. - * Note: entries for the same element separated by another element are considered separately. - * [{"count":1, "value":"Zr"}, {"count":23, "value":"H"}, {"count":11, "value":"Zr"}, {"count":1, "value":"H"}] - */ - get elementCounts() { - const elementCounts = []; - this.elements.forEach((element, index) => { - const previousElement = this.elements[index - 1]; - if (previousElement && previousElement.value === element.value) { - const previousElementCount = elementCounts[elementCounts.length - 1]; - previousElementCount.count += 1; - } - else { - elementCounts.push({ - count: 1, - value: element.value, - }); - } - }); - return elementCounts; - } - /** - * Reduced formula in IUPAC format. E.g., Na2SO4 - */ - get formula() { - const counts = this.uniqueElementCountsSortedByElectronegativity; - const countsValues = (0, lodash_1.values)(counts); - const gcd = countsValues.length > 1 ? utils_1.Utils.math.gcd(...countsValues) : countsValues[0]; - return (0, lodash_1.toPairs)(counts) - .map(([element, count]) => element + (count / gcd === 1 ? "" : count / gcd)) - .reduce((acc, part) => acc + part, ""); - } - /** - * Returns the unit cell formula as object `{ "Fe": 4.0, "O": 8.0, "Li": 2.0}` - */ - get unitCellFormula() { - const counts = this.uniqueElementCountsSortedByElectronegativity; - return (0, lodash_1.toPairs)(counts) - .map(([element, count]) => element + (count === 1 ? "" : count)) - .reduce((acc, part) => acc + part, ""); - } - /** - * Returns a nested array with elements and their corresponding coordinates - * @example Output: [ ["Si", [0,0,0]], ["Si", [0.5,0.5,0.5]] ] - */ - get elementsAndCoordinatesArray() { - return this._elements.values.map((element, idx) => { - const coordinate = this.getCoordinateValueByIndex(idx); - return [element, coordinate]; - }); - } - /** - * Returns a nested array with elements and their corresponding coordinates with labels - * @example Output: [ ["Si", [0,0,0], ['1']], ["Si", [0.5,0.5,0.5]] , ['2']] - */ - get elementsAndCoordinatesAndLabelsArray() { - return this._elements.values.map((element, idx) => { - const coordinate = this.getCoordinateValueByIndex(idx); - const atomicLabel = this.atomicLabelsArray[idx]; - return [element, coordinate, atomicLabel]; - }); - } - /** - * @summary Concatenates elements and sorts them in alphanumeric order. - * E.g., - * ``` - * elements: [{id: 0, value: 'Si'}, {id: 1, value: 'Si'}] - * coordinates: [{id: 0, value: [1,0,0]}, {id: 1, value: [0, 1, 0]}] - * - * result: "Si 0,1,0;Si 1,0,0" - * ``` - * This guarantees the independence from the order in the elements array. - */ - getAsSortedString() { - const clsInstance = this.clone(); - clsInstance.toStandardRepresentation(); - const standardRep = clsInstance.elementsAndCoordinatesAndLabelsArray.map((entry) => { - const element = entry[0]; - const coordinate = entry[1]; - const atomicLabel = entry[2]; - const toleratedCoordinate = coordinate.map((x) => utils_1.Utils.math.roundCustom(x, constants_1.HASH_TOLERANCE)); - return `${element}${atomicLabel} ${toleratedCoordinate.join()}`; - }); - return `${standardRep.sort().join(";")};`; - } - /** - * Returns a string for hash calculation (in crystal units) - */ - get hashString() { - const originallyInCartesianUnits = this.isInCartesianUnits; - this.toCrystal(); - const hashString = this.getAsSortedString(); - // preserve the original state - if (originallyInCartesianUnits) - this.toCartesian(); - return hashString; - } - /* Returns array of atomic labels E.g., ["1", "2", "", ""] */ - get atomicLabelsArray() { - var _a; - const labelsArray = Array.from({ length: this.elements.length }, () => ""); - // https://dev.to/maafaishal/benchmarking-for-while-forof-and-arrayforeach-using-performancenow-1jjg - if ((_a = this.labels) === null || _a === void 0 ? void 0 : _a.length) { - for (let i = 0; i < this.labels.length; i++) { - // @ts-ignore - labelsArray[this.labels[i].id] = this.labels[i].value.toString(); - } - } - return labelsArray; - } - /* Returns array of elements with labels E.g., ["Fe1", "Fe2", "O", "O"] */ - get elementsWithLabelsArray() { - return this.elements.map((element, i) => { - var _a, _b; - const label = ((_b = (_a = this.labels) === null || _a === void 0 ? void 0 : _a[i]) === null || _b === void 0 ? void 0 : _b.value) || ""; - return `${element.value}${label}`; - }); - } - /** - * Returns an array of strings with chemical elements and their atomic positions. - * E.g., ``` ['Si 0 0 0', 'Li 0.5 0.5 0.5']``` - */ - get atomicPositions() { - return this.elementsAndCoordinatesAndLabelsArray.map((entry, idx) => { - const element = entry[0]; - const coordinate = entry[1]; - const atomicLabel = this.atomicLabelsArray[idx]; - return `${element}${atomicLabel} ${coordinate}`; - }); - } - /** - * @summary Returns number of atoms in material - */ - get nAtoms() { - return this._elements.values.length; - } - // helpers - /** - * @summary Returns true if bases are equal, otherwise - false. - * @param anotherBasisClsInstance {Basis} Another Basis. - */ - isEqualTo(anotherBasisClsInstance) { - return this.hashString === anotherBasisClsInstance.hashString; - } - /** - * @summary Returns true if basis cells are equal, otherwise - false. - * @param anotherBasisClsInstance {Basis} Another Basis. - */ - hasEquivalentCellTo(anotherBasisClsInstance) { - return !this.cell.vectorArrays - .map((vector, idx) => { - return utils_1.Utils.math.vEqualWithTolerance(vector, anotherBasisClsInstance.cell.vectorArrays[idx]); - }) - .some((x) => !x); - } - /** - * @summary Returns the minimum cubic lattice size for a non-periodic structure. - * Single-atom structures use the element atomic radius floored at defaultMinimumLatticeSize. - * Multi-atom structures scale the maximum pairwise distance by 3 when W=min/max pairwise distance - * is ~1 (diatomic), otherwise by 2. - */ - getMinimumLatticeSize(defaultMinimumLatticeSize = lattice_1.defaultNonPeriodicMinimumLatticeSize) { - if (this._elements.values.length === 1) { - const elementSymbol = this._elements.getElementValueByIndex(0); - const atomicRadius = (0, periodic_table_js_1.getElementAtomicRadius)(elementSymbol); - return Math.max(defaultMinimumLatticeSize, atomicRadius); - } - const maxDistance = this.maxPairwiseDistance; - const minDistance = this.minPairwiseDistance; - const widthRatio = maxDistance > 0 ? minDistance / maxDistance : 1; - const latticeScalingFactor = utils_1.Utils.math.almostEqual(widthRatio, 1) - ? lattice_1.diatomicLatticePaddingFactor - : lattice_1.molecularLatticePaddingFactor; - const moleculeLatticeSize = maxDistance * latticeScalingFactor; - return Math.max(defaultMinimumLatticeSize, moleculeLatticeSize); - } - /** - * @summary function returns an array of overlapping atoms within specified tolerance. - */ - getOverlappingAtoms() { - // to simplify calculations, convert to cartesian coordinates - this.toCartesian(); - const { coordinates, elements } = this; - const overlaps = []; - // temporary value for overlap approximation, where atoms most certainly can't be located - const overlapCoefficient = 0.75; - coordinates.forEach((entry1, i) => { - for (let j = i + 1; j < coordinates.length; j++) { - const entry2 = coordinates[j]; - const el1 = elements[i].value; - const el2 = elements[j].value; - const tolerance = overlapCoefficient * - ((0, periodic_table_js_1.getElementAtomicRadius)(el1) + (0, periodic_table_js_1.getElementAtomicRadius)(el2)); // in angstroms - // @ts-ignore - const distance = utils_1.Utils.math.vDist(entry1.value, entry2.value); - if (distance < tolerance) { - overlaps.push({ - id1: i, - id2: j, - element1: el1, - element2: el2, - }); - } - } - }); - this.toCrystal(); - return overlaps; - } - /** - * @summary function returns the max distance between pairs of basis coordinates by - * calculating the distance between pairs of basis coordinates. - * basis coordinates = [[x1, y1, z1], [x2, y2, z2], ... [xn, yn, zn]] - * n = last set of coordinates - * n-1 = second to last set of coordinates - * - * Iterate through pairs without redundancy. - * pair 0,1 pair 0,2 pair 0,3 ... pair 0,n - * - pair 1,2 pair 1,3 ... pair 1,n - * - - - pair 2,3 ... pair 2,n - * - - - ... ... - * - - - ... ... pair n-1, n - * - */ - get maxPairwiseDistance() { - return this.getPairwiseDistanceExtremum("max"); - } - get minPairwiseDistance() { - return this.getPairwiseDistanceExtremum("min"); - } - getPairwiseDistanceExtremum(extremum) { - const originalUnits = this.units; - this.toCartesian(); - let resultDistance = extremum === "max" ? 0 : Infinity; - if (this._elements.values.length >= 2) { - for (let i = 0; i < this._elements.values.length; i++) { - for (let j = i + 1; j < this._elements.values.length; j++) { - const distance = utils_1.Utils.math.vDist(this._coordinates.getElementValueByIndex(i), this._coordinates.getElementValueByIndex(j)); - if (distance) { - if (extremum === "max" && distance > resultDistance) { - resultDistance = distance; - } - if (extremum === "min" && distance < resultDistance) { - resultDistance = distance; - } - } - } - } - } - if (originalUnits !== constants_1.ATOMIC_COORD_UNITS.cartesian) - this.toCrystal(); - return extremum === "min" && resultDistance === Infinity ? 0 : resultDistance; - } - /** - * @summary Function takes basis coordinates and transposes them so that the values for each dimension of the - * the basis are in their own nested array. - * Then the center point for each dimension of the coordinates is calculated. - * - * initial basisCoordinates - * [[x1, y1, z1], - * [x2, y2, z2], - * [.., .., ..], - * [xn, yn, zn]] - * - * transposed basisCoordinates - * [[x1, x2, ...xn], - * [y1, y2, ...yn], - * [z1, z2, ...zn]] - * - * Returns an array = [xCenter, yCenter, zCenter] - */ - get centerOfCoordinatesPoint() { - return this._coordinates.getCenterPoint(); - } - /** - * @summary Function translates coordinates by the vector passed as an argument. - */ - translateByVector(translationVector) { - this._coordinates.translateByVector(translationVector); - } -} -exports.Basis = Basis; -Basis.defaultConfig = DEFAULT_BASIS_CONFIG; diff --git a/dist/js/basis/constrained_basis.d.ts b/dist/js/basis/constrained_basis.d.ts deleted file mode 100644 index 15d447456..000000000 --- a/dist/js/basis/constrained_basis.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { AtomicConstraintsSchema, BasisConstrainedSchema } from "@mat3ra/esse/dist/js/types"; -import { Cell } from "../cell/cell"; -import { AtomicConstraints, AtomicConstraintValue } from "../constraints/constraints"; -import { Basis, ElementsAndCoordinatesConfig } from "./basis"; -import { AtomicCoordinateValue } from "./coordinates"; -import { AtomicElementValue } from "./elements"; -import { AtomicLabelValue } from "./labels"; -export interface ConstrainedBasisConfig extends BasisConstrainedSchema { - cell?: Cell; - isEmpty?: boolean; -} -export interface ElementsCoordinatesAndConstraintsConfig extends ElementsAndCoordinatesConfig { - constraints: AtomicConstraintValue[]; -} -/** - * @summary Extension of the Basis class able to deal with atomic constraints. - * @extends Basis - */ -export declare class ConstrainedBasis extends Basis { - private _constraints; - constructor(config: ConstrainedBasisConfig); - static fromElementsCoordinatesAndConstraints(config: ElementsCoordinatesAndConstraintsConfig): ConstrainedBasis; - get constraints(): AtomicConstraintsSchema; - set constraints(constraints: AtomicConstraintsSchema); - get AtomicConstraints(): AtomicConstraints; - toJSON(exclude?: (keyof ConstrainedBasisConfig)[]): ConstrainedBasisConfig; - getConstraintByIndex(idx: number): AtomicConstraintValue; - getConstraintById(id: number): AtomicConstraintValue; - /** - * Helper function returning a nested array with [element, coordinates, constraints] as elements - */ - get elementsCoordinatesConstraintsArray(): [ - AtomicElementValue, - AtomicLabelValue, - AtomicCoordinateValue, - AtomicConstraintValue - ][]; - /** - * Returns an array with atomic positions (with constraints) per atom stored as strings. - * E.g., ``` ['Si 0 0 0 0 1 0', 'Li 0.5 0.5 0.5 1 0 1']``` - */ - getAtomicPositionsWithConstraintsAsStrings(coordinatePrintFormat?: string, precision?: number): string[]; - removeAllAtoms(): void; -} diff --git a/dist/js/basis/constrained_basis.js b/dist/js/basis/constrained_basis.js deleted file mode 100644 index f29ca0af8..000000000 --- a/dist/js/basis/constrained_basis.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConstrainedBasis = void 0; -const constraints_1 = require("../constraints/constraints"); -const basis_1 = require("./basis"); -const coordinates_1 = require("./coordinates"); -const helpers_1 = require("./helpers"); -/** - * @summary Extension of the Basis class able to deal with atomic constraints. - * @extends Basis - */ -class ConstrainedBasis extends basis_1.Basis { - constructor(config) { - var _a; - super(config); - this._constraints = constraints_1.AtomicConstraints.fromObjects((_a = config.constraints) !== null && _a !== void 0 ? _a : []); // `constraints` is an Array with ids - } - static fromElementsCoordinatesAndConstraints(config) { - const basisConfig = this._convertValuesToConfig(config); - const constraints = constraints_1.AtomicConstraints.fromValues(config.constraints); - return new this({ - ...basisConfig, - constraints: constraints.toJSON(), - }); - } - get constraints() { - return this._constraints.toJSON(); - } - set constraints(constraints) { - this._constraints = constraints_1.AtomicConstraints.fromObjects(constraints); - } - get AtomicConstraints() { - return constraints_1.AtomicConstraints.fromObjects(this.constraints); - } - toJSON(exclude = ["cell"]) { - return { - ...super.toJSON(exclude), - constraints: this.constraints, - }; - } - getConstraintByIndex(idx) { - return this._constraints.getElementValueByIndex(idx) || [true, true, true]; - } - getConstraintById(id) { - return this._constraints.getElementValueById(id) || [true, true, true]; - } - /** - * Helper function returning a nested array with [element, coordinates, constraints] as elements - */ - get elementsCoordinatesConstraintsArray() { - return this._elements.values.map((element, idx) => { - const coordinate = this.getCoordinateValueByIndex(idx); - const constraint = this.getConstraintByIndex(idx); - const label = this.atomicLabelsArray[idx]; - return [element, label, coordinate, constraint]; - }); - } - /** - * Returns an array with atomic positions (with constraints) per atom stored as strings. - * E.g., ``` ['Si 0 0 0 0 1 0', 'Li 0.5 0.5 0.5 1 0 1']``` - */ - getAtomicPositionsWithConstraintsAsStrings(coordinatePrintFormat, precision) { - const omitConstraints = this._constraints.areUnconstrained; - return this.elementsCoordinatesConstraintsArray.map(([element, label, coordinate, constraint]) => { - const _elementWithLabel = new helpers_1.ElementWithLabel({ element, label }); - const _coordinate = coordinates_1.Coordinate.fromValueAndId(coordinate); - const _constraint = constraints_1.Constraint.fromValueAndId(constraint); - return [ - _elementWithLabel.prettyPrint(), - _coordinate.prettyPrint(coordinatePrintFormat, precision), - omitConstraints ? "" : _constraint.prettyPrint(), - ].join(" "); - }); - } - removeAllAtoms() { - super.removeAllAtoms(); - this.constraints = []; - } -} -exports.ConstrainedBasis = ConstrainedBasis; diff --git a/dist/js/basis/coordinates.d.ts b/dist/js/basis/coordinates.d.ts deleted file mode 100644 index 260a0b8c6..000000000 --- a/dist/js/basis/coordinates.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { RoundedArrayWithIds, RoundedValueWithId } from "@mat3ra/code"; -import { AtomicCoordinateSchema, Coordinate3DSchema, Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -export type AtomicCoordinateValue = AtomicCoordinateSchema["value"]; -type AxisType = "x" | "y" | "z"; -export declare class Coordinate extends RoundedValueWithId { - value: AtomicCoordinateValue; - constructor({ value, id }: AtomicCoordinateSchema); - getValueAlongAxis(axis?: AxisType): number; - translateByVector(vectorAsArray: Vector3DSchema): Coordinate; - get valueRounded(): number[]; - getValueRoundedWithPrecision(precision: number): number[]; - prettyPrint(format?: string, precision?: number): string; -} -export declare class Coordinates extends RoundedArrayWithIds { - getValuesAlongAxis(axis?: AxisType): number[]; - getMaxValueAlongAxis(axis?: AxisType): number; - getMinValueAlongAxis(axis?: AxisType): number; - getExtremumValueAlongAxis(extremum?: "max" | "min", axis?: AxisType): number; - translateByVector(vector: Vector3DSchema): void; - getCenterPoint(): Vector3DSchema; -} -export {}; diff --git a/dist/js/basis/coordinates.js b/dist/js/basis/coordinates.js deleted file mode 100644 index 8b6450b64..000000000 --- a/dist/js/basis/coordinates.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Coordinates = exports.Coordinate = void 0; -const code_1 = require("@mat3ra/code"); -const utils_1 = require("@mat3ra/utils"); -const underscore_string_1 = require("underscore.string"); -class Coordinate extends code_1.RoundedValueWithId { - constructor({ value, id }) { - super(id, value); - this.value = value; - } - getValueAlongAxis(axis = "z") { - const index = { x: 0, y: 1, z: 2 }[axis]; - return this.value[index]; - } - translateByVector(vectorAsArray) { - const vector3D = new code_1.Vector3D(this.value); - this.value = vector3D.translateByVector(vectorAsArray).value; - return this; - } - get valueRounded() { - return new code_1.RoundedVector3D(this.value).valueRounded; - } - getValueRoundedWithPrecision(precision) { - const RoundedInstance = code_1.RoundedVector3D; - RoundedInstance.roundPrecision = precision; - return new RoundedInstance(this.value).valueRounded; - } - prettyPrint(format = "%14.9f", precision = this.precision) { - return this.getValueRoundedWithPrecision(precision) - .map((x) => (0, underscore_string_1.sprintf)(format, x)) - .join(" "); - } -} -exports.Coordinate = Coordinate; -class Coordinates extends code_1.RoundedArrayWithIds { - getValuesAlongAxis(axis = "z") { - return this.values.map((coord) => { - const coordinate = Coordinate.fromValueAndId(coord); - return coordinate.getValueAlongAxis(axis); - }); - } - getMaxValueAlongAxis(axis = "z") { - return Math.max(...this.getValuesAlongAxis(axis)); - } - getMinValueAlongAxis(axis = "z") { - return Math.min(...this.getValuesAlongAxis(axis)); - } - getExtremumValueAlongAxis(extremum = "max", axis = "z") { - return extremum === "max" - ? this.getMaxValueAlongAxis(axis) - : this.getMinValueAlongAxis(axis); - } - translateByVector(vector) { - this.mapArrayInPlace((x) => { - const coordinate = Coordinate.fromValueAndId(x); - return coordinate.translateByVector(vector).value; - }); - } - getCenterPoint() { - const transposed = utils_1.Utils.math.transpose(this.values); - const center = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - const axisCoords = transposed[i]; - const sum = axisCoords.reduce((a, b) => a + b, 0); - center[i] = sum / this.values.length; - } - return center; - } -} -exports.Coordinates = Coordinates; diff --git a/dist/js/basis/elements.d.ts b/dist/js/basis/elements.d.ts deleted file mode 100644 index 5bfdce3c9..000000000 --- a/dist/js/basis/elements.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ArrayWithIds, ValueWithId } from "@mat3ra/code"; -import { AtomicElementSchema } from "@mat3ra/esse/dist/js/types"; -export type AtomicElementValue = AtomicElementSchema["value"]; -export declare class Element extends ValueWithId { - value: AtomicElementValue; - constructor({ value, id }: AtomicElementSchema); - prettyPrint(): string; -} -export declare class Elements extends ArrayWithIds { - getUnique(): string[]; -} diff --git a/dist/js/basis/elements.js b/dist/js/basis/elements.js deleted file mode 100644 index 13e92bcd1..000000000 --- a/dist/js/basis/elements.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Elements = exports.Element = void 0; -const code_1 = require("@mat3ra/code"); -const lodash_1 = require("lodash"); -class Element extends code_1.ValueWithId { - constructor({ value, id }) { - super({ id, value }); - this.value = value; - } - prettyPrint() { - return this.value; - } -} -exports.Element = Element; -class Elements extends code_1.ArrayWithIds { - getUnique() { - return (0, lodash_1.uniq)(this.values.map((element) => element)); - } -} -exports.Elements = Elements; diff --git a/dist/js/basis/helpers.d.ts b/dist/js/basis/helpers.d.ts deleted file mode 100644 index 13fed9e1d..000000000 --- a/dist/js/basis/helpers.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { AtomicElementValue } from "./elements"; -import { AtomicLabelValue } from "./labels"; -export declare class ElementWithLabel { - element: AtomicElementValue; - label: AtomicLabelValue; - constructor({ element, label }: { - element: AtomicElementValue; - label: AtomicLabelValue; - }); - prettyPrint(): string; -} diff --git a/dist/js/basis/helpers.js b/dist/js/basis/helpers.js deleted file mode 100644 index 08aaa7496..000000000 --- a/dist/js/basis/helpers.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ElementWithLabel = void 0; -const underscore_string_1 = __importDefault(require("underscore.string")); -class ElementWithLabel { - constructor({ element, label }) { - this.element = element; - this.label = label; - } - prettyPrint() { - const elementWithLabel = `${this.element}${this.label}`; - return underscore_string_1.default.sprintf("%-3s", elementWithLabel); - } -} -exports.ElementWithLabel = ElementWithLabel; diff --git a/dist/js/basis/labels.d.ts b/dist/js/basis/labels.d.ts deleted file mode 100644 index 15e8e7a4d..000000000 --- a/dist/js/basis/labels.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { ArrayWithIds } from "@mat3ra/code"; -import { AtomicLabelSchema } from "@mat3ra/esse/dist/js/types"; -export type AtomicLabelValue = AtomicLabelSchema["value"]; -export declare class Labels extends ArrayWithIds { -} diff --git a/dist/js/basis/labels.js b/dist/js/basis/labels.js deleted file mode 100644 index 292a8c320..000000000 --- a/dist/js/basis/labels.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Labels = void 0; -const code_1 = require("@mat3ra/code"); -class Labels extends code_1.ArrayWithIds { -} -exports.Labels = Labels; diff --git a/dist/js/cell/cell.d.ts b/dist/js/cell/cell.d.ts deleted file mode 100644 index 0fbaae0bb..000000000 --- a/dist/js/cell/cell.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { RoundedVector3D } from "@mat3ra/code"; -import { Coordinate3DSchema, LatticeVectorsSchema as CellSchema, Matrix3X3Schema, Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -export declare class Cell implements CellSchema { - static RoundedVector3DClassReference: typeof RoundedVector3D; - static roundPrecision: number; - static tolerance: number; - static defaultConfig: CellSchema; - a: CellSchema["a"]; - b: CellSchema["b"]; - c: CellSchema["c"]; - alat: number; - units: CellSchema["units"]; - constructor(config?: CellSchema); - static fromVectorsArray(vectors: Matrix3X3Schema): Cell; - get _a(): RoundedVector3D; - get _b(): RoundedVector3D; - get _c(): RoundedVector3D; - get vectorArrays(): Matrix3X3Schema; - get vectorArraysRounded(): Matrix3X3Schema; - get volume(): number; - get volumeRounded(): number; - clone(): Cell; - cloneAndScaleByMatrix(matrix: Matrix3X3Schema): Cell; - convertPointToCartesian(point: Coordinate3DSchema): Coordinate3DSchema; - convertPointToCrystal(point: Coordinate3DSchema): Coordinate3DSchema; - isPointInsideCellCartesian(point: Coordinate3DSchema): boolean; - isPointInsideCellCrystal(point: Coordinate3DSchema): boolean; - isPointInsideCell(point: Coordinate3DSchema, useCrystal?: boolean): boolean; - getMostCollinearVectorIndex(testVector: Vector3DSchema): number; - scaleByMatrix(matrix: number[][]): void; - toJSON(): CellSchema; -} diff --git a/dist/js/cell/cell.js b/dist/js/cell/cell.js deleted file mode 100644 index 60554aa25..000000000 --- a/dist/js/cell/cell.js +++ /dev/null @@ -1,113 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Cell = void 0; -const code_1 = require("@mat3ra/code"); -const utils_1 = require("@mat3ra/utils"); -const constants_1 = __importDefault(require("../constants")); -const MATRIX = utils_1.Utils.math.matrix; -const MULT = utils_1.Utils.math.multiply; -const INV = utils_1.Utils.math.inv; -// @ts-ignore -const MATRIX_MULT = (...args) => MULT(...args.map((x) => MATRIX(x))).toArray(); -class Cell { - constructor(config = Cell.defaultConfig) { - this.alat = 1; - this.units = "angstrom"; - const { a, b, c } = config; - this.a = a; - this.b = b; - this.c = c; - } - static fromVectorsArray(vectors) { - return new Cell({ - a: vectors[0], - b: vectors[1], - c: vectors[2], - }); - } - get _a() { - return new Cell.RoundedVector3DClassReference(this.a); - } - get _b() { - return new Cell.RoundedVector3DClassReference(this.b); - } - get _c() { - return new Cell.RoundedVector3DClassReference(this.c); - } - get vectorArrays() { - return [this._a.value, this._b.value, this._c.value]; - } - get vectorArraysRounded() { - return [this._a.valueRounded, this._b.valueRounded, this._c.valueRounded]; - } - get volume() { - return utils_1.Utils.math.det(this.vectorArrays); - } - get volumeRounded() { - return utils_1.Utils.math.roundArrayOrNumber(this.volume, Cell.roundPrecision); - } - clone() { - return new Cell({ a: this.a, b: this.b, c: this.c }); - } - cloneAndScaleByMatrix(matrix) { - const newCell = this.clone(); - newCell.scaleByMatrix(matrix); - return newCell; - } - convertPointToCartesian(point) { - return MULT(point, this.vectorArrays); - } - convertPointToCrystal(point) { - return MULT(point, INV(this.vectorArrays)); - } - isPointInsideCellCartesian(point) { - const { tolerance } = this.constructor; - return (this.convertPointToCrystal(point) - .map((c) => utils_1.Utils.math.isBetweenZeroInclusiveAndOne(c, tolerance)) - // @ts-ignore - .reduce((a, b) => a && b)); - } - // eslint-disable-next-line class-methods-use-this - isPointInsideCellCrystal(point) { - const { tolerance } = this.constructor; - return (point - .map((c) => utils_1.Utils.math.isBetweenZeroInclusiveAndOne(c, tolerance)) - // @ts-ignore - .reduce((a, b) => a && b)); - } - isPointInsideCell(point, useCrystal = false) { - if (useCrystal) { - return this.isPointInsideCellCrystal(point); - } - return this.isPointInsideCellCartesian(point); - } - getMostCollinearVectorIndex(testVector) { - const angles = this.vectorArrays.map((v) => utils_1.Utils.math.angleUpTo90(v, testVector, "deg")); - return angles.findIndex((el) => el === utils_1.Utils.math.min(angles)); - } - scaleByMatrix(matrix) { - // @ts-ignore - mathjs v12 multiply return type is broader than runtime - [this.a, this.b, this.c] = MATRIX_MULT(matrix, this.vectorArrays); - } - toJSON() { - return { - a: this._a.toJSON(), - b: this._b.toJSON(), - c: this._c.toJSON(), - alat: this.alat, - units: this.units, - }; - } -} -exports.Cell = Cell; -Cell.RoundedVector3DClassReference = code_1.RoundedVector3D; -Cell.roundPrecision = 9; -Cell.tolerance = constants_1.default.tolerance.length; // in crystal coordinates -Cell.defaultConfig = { - a: [1.0, 0, 0], - b: [0, 1.0, 0], - c: [0, 0, 1.0], -}; diff --git a/dist/js/cell/conventional_cell.d.ts b/dist/js/cell/conventional_cell.d.ts deleted file mode 100644 index b5102cf8e..000000000 --- a/dist/js/cell/conventional_cell.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { LatticeSchema, LatticeTypeEnum, Matrix3X3Schema } from "@mat3ra/esse/dist/js/types"; -export declare const PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIERS: Record; -export declare const PRIMITIVE_TO_CONVENTIONAL_CELL_LATTICE_TYPES: { - [key in LatticeTypeEnum]: LatticeTypeEnum; -}; -export declare function isConventionalCellSameAsPrimitiveForLatticeType(latticeType: LatticeSchema["type"]): boolean; diff --git a/dist/js/cell/conventional_cell.js b/dist/js/cell/conventional_cell.js deleted file mode 100644 index a03c7fc0f..000000000 --- a/dist/js/cell/conventional_cell.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PRIMITIVE_TO_CONVENTIONAL_CELL_LATTICE_TYPES = exports.PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIERS = void 0; -exports.isConventionalCellSameAsPrimitiveForLatticeType = isConventionalCellSameAsPrimitiveForLatticeType; -/** - * Routines for calculating conventional cell vectors from primitive cell Bravais parameters. - * Following Setyawan, W., & Curtarolo, S. (2010). doi:10.1016/j.commatsci.2010.05.010 - */ -const unitMatrix = [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1], -]; -// (Conventional cellVectors) = (Primitive cellVectors) * (PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIER matrix) -exports.PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIERS = { - // PRIMITIVE => CONVENTIONAL - CUB: unitMatrix, - FCC: [ - [-1, 1, 1], - [1, -1, 1], - [1, 1, -1], - ], - BCC: [ - [0, 1, 1], - [1, 0, 1], - [1, 1, 0], - ], - TET: unitMatrix, - BCT: [ - [0, 1, 1], - [1, 0, 1], - [1, 1, 0], - ], - ORC: unitMatrix, - ORCF: [ - [-1, 1, 1], - [1, -1, 1], - [1, 1, -1], - ], - ORCI: [ - [0, 1, 1], - [1, 0, 1], - [1, 1, 0], - ], - ORCC: [ - [1, -1, 0], - [1, 1, 0], - [0, 0, 1], - ], - HEX: unitMatrix, - RHL: unitMatrix, - MCL: unitMatrix, - MCLC: [ - [1, -1, 0], - [1, 1, 0], - [0, 0, 1], - ], - TRI: unitMatrix, -}; -exports.PRIMITIVE_TO_CONVENTIONAL_CELL_LATTICE_TYPES = { - // PRIMITIVE => CONVENTIONAL - CUB: "CUB", - FCC: "CUB", - BCC: "CUB", - TET: "TET", - BCT: "TET", - ORC: "ORC", - ORCF: "ORC", - ORCI: "ORC", - ORCC: "ORC", - HEX: "HEX", - RHL: "RHL", - MCL: "MCL", - MCLC: "MCL", - TRI: "TRI", -}; -function isConventionalCellSameAsPrimitiveForLatticeType(latticeType) { - const multiplier = exports.PRIMITIVE_TO_CONVENTIONAL_CELL_MULTIPLIERS[latticeType || "TRI"]; - return multiplier === unitMatrix; -} diff --git a/dist/js/cell/primitive_cell.d.ts b/dist/js/cell/primitive_cell.d.ts deleted file mode 100644 index 12b9ee1f7..000000000 --- a/dist/js/cell/primitive_cell.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { LatticeSchema, Matrix3X3Schema } from "@mat3ra/esse/dist/js/types"; -/** - * Returns lattice vectors for a primitive cell for a lattice. - * @param latticeConfig - Lattice config. - * @return Cell.vectorsAsArray - */ -export declare function getPrimitiveLatticeVectorsFromConfig(latticeConfig: LatticeSchema): Matrix3X3Schema; diff --git a/dist/js/cell/primitive_cell.js b/dist/js/cell/primitive_cell.js deleted file mode 100644 index 7d15dd6bc..000000000 --- a/dist/js/cell/primitive_cell.js +++ /dev/null @@ -1,144 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPrimitiveLatticeVectorsFromConfig = getPrimitiveLatticeVectorsFromConfig; -const utils_1 = require("@mat3ra/utils"); -/** - * Routines for calculating primitive cell vectors from conventional cell Bravais parameters. - * Following Setyawan, W., & Curtarolo, S. (2010). doi:10.1016/j.commatsci.2010.05.010 - */ -const PRIMITIVE_CELLS = { - CUB: ({ a }) => { - return [ - [a, 0, 0], - [0, a, 0], - [0, 0, a], - ]; - }, - FCC: ({ a }) => { - return [ - [0.0, a / 2, a / 2], - [a / 2, 0.0, a / 2], - [a / 2, a / 2, 0.0], - ]; - }, - BCC: ({ a }) => { - return [ - [-a / 2, a / 2, a / 2], - [a / 2, -a / 2, a / 2], - [a / 2, a / 2, -a / 2], - ]; - }, - TET: ({ a, c }) => { - return [ - [a, 0, 0], - [0, a, 0], - [0, 0, c], - ]; - }, - BCT: ({ a, c }) => { - return [ - [-a / 2, a / 2, c / 2], - [a / 2, -a / 2, c / 2], - [a / 2, a / 2, -c / 2], - ]; - }, - ORC: ({ a, b, c }) => { - return [ - [a, 0, 0], - [0, b, 0], - [0, 0, c], - ]; - }, - ORCF: ({ a, b, c }) => { - return [ - [0, b / 2, c / 2], - [a / 2, 0, c / 2], - [a / 2, b / 2, 0], - ]; - }, - ORCI: ({ a, b, c }) => { - return [ - [-a / 2, b / 2, c / 2], - [a / 2, -b / 2, c / 2], - [a / 2, b / 2, -c / 2], - ]; - }, - ORCC: ({ a, b, c }) => { - return [ - [a / 2, b / 2, 0], - [-a / 2, b / 2, 0], - [0, 0, c], - ]; - }, - HEX: ({ a, c }) => { - return [ - [a / 2, (-a * Number(utils_1.Utils.math.sqrt(3))) / 2, 0], - [a / 2, (a * Number(utils_1.Utils.math.sqrt(3))) / 2, 0], - [0, 0, c], - ]; - }, - RHL: ({ a, alpha }) => { - const cosAlpha = Number(utils_1.Utils.math.cos((alpha / 180) * Number(utils_1.Utils.math.PI))); - const cosHalfAlpha = Number(utils_1.Utils.math.sqrt((1 / 2) * (1 + cosAlpha))); - const sinHalfAlpha = Number(utils_1.Utils.math.sqrt((1 / 2) * (1 - cosAlpha))); - return [ - [a * cosHalfAlpha, -a * sinHalfAlpha, 0.0], - [a * cosHalfAlpha, a * sinHalfAlpha, 0.0], - [ - (a * cosAlpha) / cosHalfAlpha, - 0.0, - a * - Number(utils_1.Utils.math.sqrt(1 - (cosAlpha * cosAlpha) / (cosHalfAlpha * cosHalfAlpha))), - ], - ]; - }, - MCL: ({ a, b, c, alpha }) => { - const cosAlpha = Number(utils_1.Utils.math.cos((alpha / 180) * Number(utils_1.Utils.math.PI))); - return [ - [a, 0, 0], - [0, b, 0], - [0, c * cosAlpha, c * Number(utils_1.Utils.math.sqrt(1 - cosAlpha * cosAlpha))], - ]; - }, - MCLC: ({ a, b, c, alpha }) => { - const cosAlpha = Number(utils_1.Utils.math.cos((alpha / 180) * Number(utils_1.Utils.math.PI))); - return [ - [a / 2, b / 2, 0], - [-a / 2, b / 2, 0], - [0, c * cosAlpha, c * Number(utils_1.Utils.math.sqrt(1 - cosAlpha * cosAlpha))], - ]; - }, - // Algorithm from http://pymatgen.org/_modules/pymatgen/core/lattice.html (from_params) - TRI: ({ a, b, c, alpha, beta, gamma }) => { - // convert angles to Radians - // eslint-disable-next-line no-param-reassign - [alpha, beta, gamma] = [alpha, beta, gamma].map((x) => Number(utils_1.Utils.math.unit(x, "degree").to("rad").value)); - const [cosAlpha, cosBeta, cosGamma] = [alpha, beta, gamma].map((x) => Number(utils_1.Utils.math.cos(x))); - const [sinAlpha, sinBeta] = [alpha, beta].map((x) => Number(utils_1.Utils.math.sin(x))); - let acosArg = (cosAlpha * cosBeta - cosGamma) / (sinAlpha * sinBeta); - if (acosArg < -1) { - acosArg = -1; - } - else if (acosArg > 1) { - acosArg = 1; - } - const gammaStar = Number(utils_1.Utils.math.acos(acosArg)); - const cosGammaStar = Number(utils_1.Utils.math.cos(gammaStar)); - const sinGammaStar = Number(utils_1.Utils.math.sin(gammaStar)); - return [ - [a * sinBeta, 0.0, a * cosBeta], - [-b * sinAlpha * cosGammaStar, b * sinAlpha * sinGammaStar, b * cosAlpha], - [0.0, 0.0, c], - ]; - }, -}; -/** - * Returns lattice vectors for a primitive cell for a lattice. - * @param latticeConfig - Lattice config. - * @return Cell.vectorsAsArray - */ -function getPrimitiveLatticeVectorsFromConfig(latticeConfig) { - const primitiveCellGenerator = PRIMITIVE_CELLS[latticeConfig.type || "TRI"]; - const [vectorA, vectorB, vectorC] = primitiveCellGenerator(latticeConfig); - return [vectorA, vectorB, vectorC]; -} diff --git a/dist/js/constants.d.ts b/dist/js/constants.d.ts deleted file mode 100644 index e06aa864b..000000000 --- a/dist/js/constants.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "@mat3ra/code/dist/js/constants"; -export { default } from "@mat3ra/code/dist/js/constants"; diff --git a/dist/js/constants.js b/dist/js/constants.js deleted file mode 100644 index c8e634e1b..000000000 --- a/dist/js/constants.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = void 0; -// TODO: adjust the imports and remove the need for re-exporting -__exportStar(require("@mat3ra/code/dist/js/constants"), exports); -// eslint-disable-next-line no-restricted-exports -var constants_1 = require("@mat3ra/code/dist/js/constants"); -Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(constants_1).default; } }); diff --git a/dist/js/constants/molecule.d.ts b/dist/js/constants/molecule.d.ts deleted file mode 100644 index 090912fc0..000000000 --- a/dist/js/constants/molecule.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Constants for molecule handling and precision. - * Source of truth: /constants.json at repository root - * - * These values are duplicated here for TypeScript compilation. - * When updating these, also update constants.json. - */ -export declare const defaultNonPeriodicMinimumLatticeSize = 3; -export declare const diatomicLatticePaddingFactor = 3; -export declare const molecularLatticePaddingFactor = 2; -export declare const PRECISION_MAP: { - coordinatesCrystal: number; - coordinatesCartesian: number; - latticeLengths: number; - latticeAngles: number; -}; diff --git a/dist/js/constants/molecule.js b/dist/js/constants/molecule.js deleted file mode 100644 index 64dc489fb..000000000 --- a/dist/js/constants/molecule.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -/** - * Constants for molecule handling and precision. - * Source of truth: /constants.json at repository root - * - * These values are duplicated here for TypeScript compilation. - * When updating these, also update constants.json. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PRECISION_MAP = exports.molecularLatticePaddingFactor = exports.diatomicLatticePaddingFactor = exports.defaultNonPeriodicMinimumLatticeSize = void 0; -exports.defaultNonPeriodicMinimumLatticeSize = 3.0; -exports.diatomicLatticePaddingFactor = 3.0; -exports.molecularLatticePaddingFactor = 2.0; -exports.PRECISION_MAP = { - coordinatesCrystal: 9, - coordinatesCartesian: 6, - latticeLengths: 6, - latticeAngles: 4, -}; diff --git a/dist/js/constraints/constraints.d.ts b/dist/js/constraints/constraints.d.ts deleted file mode 100644 index 4e3f0b703..000000000 --- a/dist/js/constraints/constraints.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ArrayWithIds, ValueWithId } from "@mat3ra/code"; -import { AtomicConstraintSchema } from "@mat3ra/esse/dist/js/types"; -export type AtomicConstraintValue = AtomicConstraintSchema["value"]; -export declare class Constraint extends ValueWithId { - value: AtomicConstraintValue; - constructor({ value, id }: AtomicConstraintSchema); - getValueAsString(): string; - prettyPrint(): string; - isUnconstrained(): boolean; -} -export declare class AtomicConstraints extends ArrayWithIds { - /** - * Get constraints for an atom with index as string. - * @param idx - atom index. - * @param mapFn (OPTIONAL) - a function to be applied to each constraint. By default 0 or 1 is returned. - */ - getAsStringByIndex(idx: number, mapFn?: (val: boolean) => string): string; - get areUnconstrained(): boolean; -} diff --git a/dist/js/constraints/constraints.js b/dist/js/constraints/constraints.js deleted file mode 100644 index de3467938..000000000 --- a/dist/js/constraints/constraints.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AtomicConstraints = exports.Constraint = void 0; -const code_1 = require("@mat3ra/code"); -class Constraint extends code_1.ValueWithId { - constructor({ value, id }) { - super({ id, value }); - this.value = value; - } - getValueAsString() { - return this.value.map((x) => (x ? 1 : 0)).join(" "); - } - prettyPrint() { - return this.value.map((x) => (x ? 1 : 0)).join(" "); - } - // By default, the constraint is unconstrained if all values are 1/true. - isUnconstrained() { - return this.value.every((val) => val); - } -} -exports.Constraint = Constraint; -class AtomicConstraints extends code_1.ArrayWithIds { - /** - * Get constraints for an atom with index as string. - * @param idx - atom index. - * @param mapFn (OPTIONAL) - a function to be applied to each constraint. By default 0 or 1 is returned. - */ - getAsStringByIndex(idx, mapFn = (val) => (val ? "1" : "0")) { - const constraints = this.getElementValueByIndex(idx); - return constraints ? constraints.map(mapFn).join(" ") : ""; - } - get areUnconstrained() { - return this.values.every((constraint) => { - const _constraint = Constraint.fromValueAndId(constraint); - return _constraint.isUnconstrained(); - }); - } -} -exports.AtomicConstraints = AtomicConstraints; diff --git a/dist/js/data/reciprocal_paths.json b/dist/js/data/reciprocal_paths.json deleted file mode 100644 index 5c95874d9..000000000 --- a/dist/js/data/reciprocal_paths.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "CUB": [ - ["Γ", "X", "M", "Γ", "R", "X"], - ["M", "R"] - ], - "BCC": [ - ["Γ", "H", "N", "Γ", "P", "H"], - ["P", "N"] - ], - "FCC": [ - ["Γ", "X", "W", "K", "Γ", "L", "U", "W", "L"], - ["U", "X"] - ], - "TET": [ - ["Γ", "X", "M", "Γ", "Z", "R", "A", "Z"], - ["X", "R"], - ["M", "A"] - ], - "BCT-1": [ - ["Γ", "X", "M", "Γ", "Z", "P", "N", "Z1", "M"], - ["X", "P"] - ], - "BCT-2": [ - ["Γ", "X", "Y", "∑", "Γ", "Z", "∑1", "N", "P", "Y1", "Z"], - ["X", "P"] - ], - "ORC": [ - ["Γ", "X", "S", "Y", "Γ", "Z", "U", "R", "T", "Z"], - ["Y", "T"], - ["U", "X"], - ["S", "R"] - ], - "ORCF-1": [ - ["Γ", "Y", "T", "Z", "Γ", "X", "A1", "Y"], - ["T", "X1"], - ["X", "A", "Z"], - ["L", "Γ"] - ], - "ORCF-2": [ - ["Γ", "Y", "C", "D", "X", "Γ", "Z", "D1", "H", "C"], - ["C1", "Z"], - ["X", "H1"], - ["H", "Y"], - ["L", "Γ"] - ], - "ORCF-3": [ - ["Γ", "Y", "T", "Z", "Γ", "X", "A1", "Y"], - ["X", "A", "Z"], - ["L", "Γ"] - ], - "ORCI": [ - ["Γ", "X", "L", "T", "W", "R", "X1", "Z", "Γ", "Y", "S", "W"], - ["L1", "Y"], - ["Y1", "Z"] - ], - "ORCC": [ - ["Γ", "X", "S", "R", "A", "Z", "Γ", "Y", "X1", "A1", "T", "Y"], - ["Z", "T"] - ], - "HEX": [ - ["Γ", "M", "K", "Γ", "A", "L", "H", "A"], - ["L", "M"], - ["K", "H"] - ], - "RHL-1": [ - ["Γ", "L", "B1"], - ["B", "Z", "Γ", "X"], - ["Q", "F", "P1", "Z"], - ["L", "P"] - ], - "RHL-2": [["Γ", "P", "Z", "Q", "Γ", "F", "P1", "Q1", "L", "Z"]], - "MCL": [ - ["Γ", "Y", "H", "C", "E", "M1", "A", "X", "H1"], - ["M", "D", "Z"], - ["Y", "D"] - ], - "MCLC-1": [ - ["Γ", "Y", "Γ", "L", "I"], - ["I1", "Z", "F1"], - ["Y", "X1"], - ["X", "Γ", "N"], - ["M", "Γ"] - ], - "MCLC-2": [ - ["Γ", "Y", "F", "L", "I"], - ["I1", "Z", "F1"], - ["N", "Γ", "M"] - ], - "MCLC-3": [ - ["Γ", "Y", "F", "H", "Z", "I", "F1"], - ["H1", "Y1", "X", "Γ", "N"], - ["M", "Γ"] - ], - "MCLC-4": [ - ["Γ", "Y", "F", "H", "Z", "I"], - ["H1", "Y1", "X", "Γ", "N"], - ["M", "Γ"] - ], - "MCLC-5": [ - ["Γ", "Y", "F", "L", "I"], - ["I1", "Z", "H", "F1"], - ["H1", "Y1", "X", "Γ", "N"], - ["M", "Γ"] - ], - "TRI": [ - ["X", "Γ", "Y"], - ["L", "Γ", "Z"], - ["N", "Γ", "M"], - ["R", "Γ"] - ] -} diff --git a/dist/js/generated/MaterialSchemaMixin.d.ts b/dist/js/generated/MaterialSchemaMixin.d.ts deleted file mode 100644 index 119a8963a..000000000 --- a/dist/js/generated/MaterialSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { InMemoryEntity } from "@mat3ra/code/dist/js/entity"; -import type { BaseInMemoryEntitySchema, MaterialPropertiesSchema } from "@mat3ra/esse/dist/js/types"; -export type MaterialSchemaMixin = MaterialPropertiesSchema; -export type MaterialInMemoryEntity = InMemoryEntity; -export declare function materialSchemaMixin(item: InMemoryEntity): asserts item is T & MaterialSchemaMixin; diff --git a/dist/js/generated/MaterialSchemaMixin.js b/dist/js/generated/MaterialSchemaMixin.js deleted file mode 100644 index 8708d831a..000000000 --- a/dist/js/generated/MaterialSchemaMixin.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.materialSchemaMixin = materialSchemaMixin; -function materialSchemaMixin(item) { - // @ts-expect-error - const properties = { - get formula() { - return this.prop("formula"); - }, - set formula(value) { - this.setProp("formula", value); - }, - get unitCellFormula() { - return this.prop("unitCellFormula"); - }, - set unitCellFormula(value) { - this.setProp("unitCellFormula", value); - }, - get basis() { - return this.requiredProp("basis"); - }, - set basis(value) { - this.setProp("basis", value); - }, - get lattice() { - return this.requiredProp("lattice"); - }, - set lattice(value) { - this.setProp("lattice", value); - }, - get derivedProperties() { - return this.prop("derivedProperties"); - }, - set derivedProperties(value) { - this.setProp("derivedProperties", value); - }, - get external() { - return this.prop("external"); - }, - set external(value) { - this.setProp("external", value); - }, - get src() { - return this.prop("src"); - }, - set src(value) { - this.setProp("src", value); - }, - get icsdId() { - return this.prop("icsdId"); - }, - set icsdId(value) { - this.setProp("icsdId", value); - }, - get isNonPeriodic() { - return this.prop("isNonPeriodic"); - }, - set isNonPeriodic(value) { - this.setProp("isNonPeriodic", value); - }, - get consistencyChecks() { - return this.prop("consistencyChecks"); - }, - set consistencyChecks(value) { - this.setProp("consistencyChecks", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/lattice/lattice.d.ts b/dist/js/lattice/lattice.d.ts deleted file mode 100644 index 7b98e0d02..000000000 --- a/dist/js/lattice/lattice.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { InMemoryEntity } from "@mat3ra/code/dist/js/entity"; -import { BaseInMemoryEntitySchema, LatticeSchema, LatticeTypeEnum, LatticeTypeExtendedEnum, LatticeVectorsSchema, Matrix3X3Schema } from "@mat3ra/esse/dist/js/types"; -import { Cell } from "../cell/cell"; -import { UnitCell } from "./unit_cell"; -/** - * Scaling factor used to calculate the new lattice size for non-periodic systems. - * The scaling factor ensures that a non-periodic structure will have have a lattice greater than the structures size. - */ -export { defaultNonPeriodicMinimumLatticeSize, diatomicLatticePaddingFactor, molecularLatticePaddingFactor, } from "../constants/molecule"; -export declare class LatticeVectors extends Cell implements LatticeVectorsSchema { -} -export type { LatticeVectorsSchema }; -type LatticeEntitySchema = LatticeSchema & BaseInMemoryEntitySchema; -export declare class Lattice extends InMemoryEntity implements LatticeSchema { - static defaultConfig: LatticeSchema; - a: LatticeSchema["a"]; - b: LatticeSchema["b"]; - c: LatticeSchema["c"]; - alpha: LatticeSchema["alpha"]; - beta: LatticeSchema["beta"]; - gamma: LatticeSchema["gamma"]; - type: LatticeTypeEnum; - units: LatticeSchema["units"]; - constructor(config?: LatticeSchema); - static fromConfig(config: object): Lattice; - static fromConfigPartial(config: LatticeSchema): Lattice; - calculateVectors(): Matrix3X3Schema; - static fromVectors(config: LatticeVectorsSchema): Lattice; - static fromVectorsArray(vectors: Matrix3X3Schema, units?: LatticeSchema["units"], type?: LatticeTypeEnum): Lattice; - get unitCell(): UnitCell; - get vectors(): LatticeVectors; - get vectorArrays(): Matrix3X3Schema; - get vectorArraysRounded(): Matrix3X3Schema; - get cellVolume(): number; - get cellVolumeRounded(): number; - /** - * Get a short label for the type of the lattice, eg. "MCLC". - */ - get typeLabel(): string; - /** - * Get a short label for the extended type of the lattice, eg. "MCLC-5". - */ - get typeExtended(): LatticeTypeExtendedEnum; - /** - * Calculate the volume of the lattice cell. - */ - get volume(): number; - static getDefaultPrimitiveLatticeConfigByType(latticeConfig: LatticeSchema): LatticeSchema & { - a: unknown; - b: unknown; - c: unknown; - alpha: unknown; - beta: unknown; - gamma: unknown; - }; - /** - * Returns a string further used for the calculation of an unique hash. - * @param isScaled - Whether to scale the vectors by the length of the first vector initially. - */ - getHashString(isScaled?: boolean): string; - /** - * Get the list of editable keys (eg. 'a', 'alpha') for the current lattice. - * @return {Object} - * @example {a: true, b: false, c: false, alpha: true, beta: false, gamma: false} - */ - get editables(): {}; - toJSON(exclude?: (keyof LatticeSchema)[]): LatticeSchema; -} diff --git a/dist/js/lattice/lattice.js b/dist/js/lattice/lattice.js deleted file mode 100644 index 6461b6ee8..000000000 --- a/dist/js/lattice/lattice.js +++ /dev/null @@ -1,278 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Lattice = exports.LatticeVectors = exports.molecularLatticePaddingFactor = exports.diatomicLatticePaddingFactor = exports.defaultNonPeriodicMinimumLatticeSize = void 0; -const entity_1 = require("@mat3ra/code/dist/js/entity"); -const utils_1 = require("@mat3ra/utils"); -const lodash = __importStar(require("lodash")); -const cell_1 = require("../cell/cell"); -const primitive_cell_1 = require("../cell/primitive_cell"); -const lattice_types_1 = require("./lattice_types"); -const unit_cell_1 = require("./unit_cell"); -const { HASH_TOLERANCE } = utils_1.Utils.constants; -/** - * Scaling factor used to calculate the new lattice size for non-periodic systems. - * The scaling factor ensures that a non-periodic structure will have have a lattice greater than the structures size. - */ -var molecule_1 = require("../constants/molecule"); -Object.defineProperty(exports, "defaultNonPeriodicMinimumLatticeSize", { enumerable: true, get: function () { return molecule_1.defaultNonPeriodicMinimumLatticeSize; } }); -Object.defineProperty(exports, "diatomicLatticePaddingFactor", { enumerable: true, get: function () { return molecule_1.diatomicLatticePaddingFactor; } }); -Object.defineProperty(exports, "molecularLatticePaddingFactor", { enumerable: true, get: function () { return molecule_1.molecularLatticePaddingFactor; } }); -class LatticeVectors extends cell_1.Cell { -} -exports.LatticeVectors = LatticeVectors; -class Lattice extends entity_1.InMemoryEntity { - constructor(config = Lattice.defaultConfig) { - super(config); - this.type = "TRI"; - const { a, b, c, alpha, beta, gamma, units, type } = config; - this.a = a; - this.b = b; - this.c = c; - this.alpha = alpha; - this.beta = beta; - this.gamma = gamma; - this.units = units; - this.type = type || "TRI"; - } - static fromConfig(config) { - const latticeConfig = config; - return new Lattice(latticeConfig); - } - static fromConfigPartial(config) { - const primitiveLatticeConfig = Lattice.getDefaultPrimitiveLatticeConfigByType(config); - return new Lattice(primitiveLatticeConfig); - } - calculateVectors() { - const { a } = this; - const { b } = this; - const { c } = this; - const alphaRad = utils_1.Utils.math.unit(this.alpha, "deg").toNumber("rad"); - const betaRad = utils_1.Utils.math.unit(this.beta, "deg").toNumber("rad"); - const gammaRad = utils_1.Utils.math.unit(this.gamma, "deg").toNumber("rad"); - const cosAlpha = utils_1.Utils.math.cos(alphaRad); - const cosBeta = utils_1.Utils.math.cos(betaRad); - const cosGamma = utils_1.Utils.math.cos(gammaRad); - const sinAlpha = utils_1.Utils.math.sin(alphaRad); - const sinBeta = utils_1.Utils.math.sin(betaRad); - const gammaStar = utils_1.Utils.math.acos((cosAlpha * cosBeta - cosGamma) / (sinAlpha * sinBeta)); - // @ts-ignore - mathjs v12 acos return type includes Complex, but inputs are always real - const cosGammaStar = utils_1.Utils.math.cos(gammaStar); - // @ts-ignore - const sinGammaStar = utils_1.Utils.math.sin(gammaStar); - const vectorA = [a * sinBeta, 0.0, a * cosBeta]; - const vectorB = [ - -b * sinAlpha * cosGammaStar, - b * sinAlpha * sinGammaStar, - b * cosAlpha, - ]; - const vectorC = [0.0, 0.0, c]; - return [vectorA, vectorB, vectorC]; - } - static fromVectors(config) { - return this.fromVectorsArray([config.a, config.b, config.c]); - } - static fromVectorsArray(vectors, units = Lattice.defaultConfig.units, type = "TRI") { - const [aVec, bVec, cVec] = vectors; - const a = utils_1.Utils.math.vlen(aVec); - const b = utils_1.Utils.math.vlen(bVec); - const c = utils_1.Utils.math.vlen(cVec); - const alpha = utils_1.Utils.math.angle(bVec, cVec, "deg"); - const beta = utils_1.Utils.math.angle(aVec, cVec, "deg"); - const gamma = utils_1.Utils.math.angle(aVec, bVec, "deg"); - return new Lattice({ - a, - b, - c, - alpha, - beta, - gamma, - units, - type, - }); - } - // TODO: remove - get unitCell() { - var _a; - const units = ((_a = this.units) === null || _a === void 0 ? void 0 : _a.length) || "angstrom"; - const vectors = [...lodash.flatten(this.vectorArrays), units]; - return new unit_cell_1.UnitCell(vectors); - } - get vectors() { - return LatticeVectors.fromVectorsArray(this.calculateVectors()); - } - get vectorArrays() { - return this.vectors.vectorArrays; - } - get vectorArraysRounded() { - return this.vectors.vectorArraysRounded; - } - get cellVolume() { - return this.vectors.volume; - } - get cellVolumeRounded() { - return this.vectors.volumeRounded; - } - /** - * Get a short label for the type of the lattice, eg. "MCLC". - */ - get typeLabel() { - return lodash.get(lattice_types_1.LATTICE_TYPE_CONFIGS.find((c) => c.code === this.type), "label", "Unknown"); - } - /** - * Get a short label for the extended type of the lattice, eg. "MCLC-5". - */ - get typeExtended() { - const { a, b, c, alpha, beta, gamma, type } = this; - const cosAlpha = utils_1.Utils.math.cos((alpha / 180) * utils_1.Utils.math.PI); - switch (type) { - case "BCT": - return c < a ? "BCT-1" : "BCT-2"; - case "ORCF": - if (1 / (a * a) >= 1 / (b * b) + 1 / (c * c)) { - return "ORCF-1"; - } - return "ORCF-2"; - case "RHL": - return cosAlpha > 0 ? "RHL-1" : "RHL-2"; - case "MCLC": - if (gamma >= 90) { - // MCLC-1,2 - return "MCLC-1"; - } - if ((b / c) * cosAlpha + ((b * b) / (a * a)) * (1 - cosAlpha * cosAlpha) <= 1) { - // MCLC-3,4 - return "MCLC-3"; - } - return "MCLC-5"; - case "TRI": - if (alpha > 90 && beta > 90 && gamma >= 90) { - // TRI-1a,2a - return "TRI_1a"; - } - return "TRI_1b"; - default: - return type; - } - } - /** - * Calculate the volume of the lattice cell. - */ - get volume() { - return utils_1.Utils.math.abs(utils_1.Utils.math.det(this.vectorArrays)); - } - /* - * Returns a "default" primitive lattice by type, with lattice parameters scaled by the length of "a", - * @param latticeConfig {Object} LatticeBravais config (see constructor) - */ - static getDefaultPrimitiveLatticeConfigByType(latticeConfig) { - const f_ = utils_1.Utils.math.roundArrayOrNumber; - // construct new primitive cell using lattice parameters and skip rounding the vectors - const vectors = (0, primitive_cell_1.getPrimitiveLatticeVectorsFromConfig)(latticeConfig); - // create new lattice from primitive cell - const newLattice = Lattice.fromVectorsArray(vectors, undefined, latticeConfig.type); - // preserve the new type and scale back the lattice parameters - const k = latticeConfig.a / newLattice.a; - return Object.assign(newLattice.toJSON(), { - a: f_(newLattice.a * k), - b: f_(newLattice.b * k), - c: f_(newLattice.c * k), - alpha: f_(newLattice.alpha), - beta: f_(newLattice.beta), - gamma: f_(newLattice.gamma), - }); - } - /** - * Returns a string further used for the calculation of an unique hash. - * @param isScaled - Whether to scale the vectors by the length of the first vector initially. - */ - getHashString(isScaled = false) { - // lattice vectors must be measured in angstroms - const scaleK = isScaled ? this.a : 1; - const scaledLattice = { - ...this, - a: this.a / scaleK, - b: this.b / scaleK, - c: this.c / scaleK, - }; - // form lattice string - return `${[ - scaledLattice.a, - scaledLattice.b, - scaledLattice.c, - scaledLattice.alpha, - scaledLattice.beta, - scaledLattice.gamma, - ] - .map((x) => utils_1.Utils.math.roundCustom(x, HASH_TOLERANCE)) - .join(";")};`; - } - /** - * Get the list of editable keys (eg. 'a', 'alpha') for the current lattice. - * @return {Object} - * @example {a: true, b: false, c: false, alpha: true, beta: false, gamma: false} - */ - get editables() { - var _a; - const object = {}; - const editablesList = (_a = lattice_types_1.LATTICE_TYPE_CONFIGS.find((entry) => entry.code === this.type)) === null || _a === void 0 ? void 0 : _a.editables; - // ["a", "gamma"] => {a: true, gamma: true} - if (editablesList) { - editablesList.forEach((element) => { - Object.assign(object, { - [element]: true, - }); - }); - } - return object; - } - toJSON(exclude = []) { - return { - ...super.toJSON(exclude), - vectors: this.vectors.toJSON(), - }; - } -} -exports.Lattice = Lattice; -Lattice.defaultConfig = { - a: 1, - b: 1, - c: 1, - alpha: 90, - beta: 90, - gamma: 90, - units: { length: "angstrom", angle: "degree" }, - type: "CUB", -}; diff --git a/dist/js/lattice/lattice_types.d.ts b/dist/js/lattice/lattice_types.d.ts deleted file mode 100644 index 52e5852bf..000000000 --- a/dist/js/lattice/lattice_types.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { LatticeTypeEnum } from "@mat3ra/esse/dist/js/types"; -export declare enum LatticeTypeExtended { - BCC = "BCC", - BCT_1 = "BCT-1", - BCT_2 = "BCT-2", - CUB = "CUB", - FCC = "FCC", - HEX = "HEX", - MCL = "MCL", - MCLC_1 = "MCLC-1", - MCLC_2 = "MCLC-2", - MCLC_3 = "MCLC-3", - MCLC_4 = "MCLC-4", - MCLC_5 = "MCLC-5", - ORC = "ORC", - ORCC = "ORCC", - ORCF_1 = "ORCF-1", - ORCF_2 = "ORCF-2", - ORCF_3 = "ORCF-3", - ORCI = "ORCI", - RHL_1 = "RHL-1", - RHL_2 = "RHL-2", - TET = "TET", - TRI_1a = "TRI_1a", - TRI_2a = "TRI_2a", - TRI_1b = "TRI_1b" -} -export interface LatticeTypeConfig { - label: string; - code: LatticeTypeEnum; - editables: string[]; - editablesConventional: string[]; -} -export declare const DEFAULT_LATTICE_UNITS: { - length: { - angstrom: string; - }; - angle: { - degree: string; - }; -}; -export declare const LATTICE_TYPE_CONFIGS: LatticeTypeConfig[]; diff --git a/dist/js/lattice/lattice_types.js b/dist/js/lattice/lattice_types.js deleted file mode 100644 index 50f74a2a1..000000000 --- a/dist/js/lattice/lattice_types.js +++ /dev/null @@ -1,127 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LATTICE_TYPE_CONFIGS = exports.DEFAULT_LATTICE_UNITS = exports.LatticeTypeExtended = void 0; -var LatticeTypeExtended; -(function (LatticeTypeExtended) { - LatticeTypeExtended["BCC"] = "BCC"; - LatticeTypeExtended["BCT_1"] = "BCT-1"; - LatticeTypeExtended["BCT_2"] = "BCT-2"; - LatticeTypeExtended["CUB"] = "CUB"; - LatticeTypeExtended["FCC"] = "FCC"; - LatticeTypeExtended["HEX"] = "HEX"; - LatticeTypeExtended["MCL"] = "MCL"; - LatticeTypeExtended["MCLC_1"] = "MCLC-1"; - LatticeTypeExtended["MCLC_2"] = "MCLC-2"; - LatticeTypeExtended["MCLC_3"] = "MCLC-3"; - LatticeTypeExtended["MCLC_4"] = "MCLC-4"; - LatticeTypeExtended["MCLC_5"] = "MCLC-5"; - LatticeTypeExtended["ORC"] = "ORC"; - LatticeTypeExtended["ORCC"] = "ORCC"; - LatticeTypeExtended["ORCF_1"] = "ORCF-1"; - LatticeTypeExtended["ORCF_2"] = "ORCF-2"; - LatticeTypeExtended["ORCF_3"] = "ORCF-3"; - LatticeTypeExtended["ORCI"] = "ORCI"; - LatticeTypeExtended["RHL_1"] = "RHL-1"; - LatticeTypeExtended["RHL_2"] = "RHL-2"; - LatticeTypeExtended["TET"] = "TET"; - LatticeTypeExtended["TRI_1a"] = "TRI_1a"; - LatticeTypeExtended["TRI_2a"] = "TRI_2a"; - LatticeTypeExtended["TRI_1b"] = "TRI_1b"; -})(LatticeTypeExtended || (exports.LatticeTypeExtended = LatticeTypeExtended = {})); -exports.DEFAULT_LATTICE_UNITS = { - // by default lattice vectors shall be measured in angstrom, angles - in degrees - length: { - angstrom: "angstrom", - }, - angle: { - degree: "degree", - }, -}; -exports.LATTICE_TYPE_CONFIGS = [ - { - label: "Simple Cubic", - code: "CUB", - // editables for primitive cell => WARNING: not tested - editables: ["a"], - // editables for conventional cell, taken from the publication above - editablesConventional: ["a"], - }, - { - label: "Face-centered Cubic", - code: "FCC", - editables: ["a"], - editablesConventional: ["a"], - }, - { - label: "Body-centered Cubic", - code: "BCC", - editables: ["a"], - editablesConventional: ["a"], - }, - { - label: "Tetragonal", - code: "TET", - editables: ["a", "c"], - editablesConventional: ["a", "c"], - }, - { - label: "Body-centered Tetragonal", - code: "BCT", - editables: ["a"], - editablesConventional: ["a", "c"], - }, - { - label: "Orthorombic", - code: "ORC", - editables: ["a", "b", "c"], - editablesConventional: ["a", "b", "c"], - }, - { - label: "Orthorombic Face-centered", - code: "ORCF", - editables: ["a", "b", "c"], - editablesConventional: ["a", "b", "c"], - }, - { - label: "Orthorombic Body-centered", - code: "ORCI", - editables: ["a", "alpha", "gamma"], - editablesConventional: ["a", "b", "c"], - }, - { - label: "Orthorombic Base-centered", - code: "ORCC", - editables: ["a", "c", "alpha"], - editablesConventional: ["a", "b", "c"], - }, - { - label: "Hexagonal", - code: "HEX", - editables: ["a", "c"], - editablesConventional: ["a", "c"], - }, - { - label: "Rhombohedral", - code: "RHL", - editables: ["a", "alpha"], - editablesConventional: ["a", "alpha"], - }, - { - label: "Monoclinic", - code: "MCL", - editables: ["a", "b", "c", "alpha"], - editablesConventional: ["a", "b", "c", "alpha"], - }, - { - label: "Monoclinic Base-centered", - code: "MCLC", - editables: ["a", "c", "alpha", "gamma"], - editablesConventional: ["a", "b", "c", "alpha"], - }, - { - label: "Triclinic", - code: "TRI", - editables: ["a", "b", "c", "alpha", "beta", "gamma"], - editablesConventional: ["a", "b", "c", "alpha", "beta", "gamma"], - }, -]; diff --git a/dist/js/lattice/reciprocal/lattice_reciprocal.d.ts b/dist/js/lattice/reciprocal/lattice_reciprocal.d.ts deleted file mode 100644 index 20e8ffc16..000000000 --- a/dist/js/lattice/reciprocal/lattice_reciprocal.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -import { Lattice } from "../lattice"; -export type KPointCoordinates = number[]; -export type KPointPath = Array<{ - point: string; - steps: number; - coordinates: KPointCoordinates; -}>; -interface SymmetryPoint { - point: string; - coordinates: KPointCoordinates; -} -interface ConversionTable { - [key: string]: { - [key: string]: number; - }; -} -export declare class ReciprocalLattice extends Lattice { - /** - * Get reciprocal vectors for the current Lattice in cartesian (2pi / a) units - * @return {Vector3DSchema[]} - */ - get reciprocalVectors(): Vector3DSchema[]; - /** - * Norms of reciprocal vectors. - */ - get reciprocalVectorNorms(): Vector3DSchema; - /** - * Ratio of reciprocal vector norms scaled by the inverse of the largest component. - */ - get reciprocalVectorRatios(): Vector3DSchema; - /** - * Get point (in crystal coordinates) in cartesian coordinates. - * @param {KPointCoordinates} point - point in 3D space - * @return {KPointCoordinates} - */ - getCartesianCoordinates(point: KPointCoordinates): KPointCoordinates; - /** - * Get the list of high-symmetry points for the current lattice. - * @return {SymmetryPoint[]} - */ - get symmetryPoints(): SymmetryPoint[]; - /** - * Get the default path in reciprocal space for the current lattice. - * @return {Array<{point: string; steps: number}>} - */ - get defaultKpointPath(): Array<{ - point: string; - steps: number; - }>; - /** - * Find/mark the high symmetry points on a list with raw data and return the edited list. - * @param {KPointCoordinates[]} dataPoints - list of point coordinates - * @return {KPointPath} - */ - extractKpointPath(dataPoints?: KPointCoordinates[]): KPointPath; - /** - * Calculate grid dimension based on reciprocal lattice vectors. - * @param {number} nPoints - Total number of points - * @param {number} index - Index of reciprocal vector - * @return {number} - Grid dimension in direction of reciprocal vector - * @todo This could be moved to a separate KGrid class. - */ - calculateDimension(nPoints: number, index: number): number; - /** - * Calculate grid dimensions from total number of k-points. - * @param {number} nKpoints - Total number of k-points. - * @return Grid dimensions - */ - getDimensionsFromPointsCount(nKpoints: number): Vector3DSchema; - get conversionTable(): ConversionTable; - /** - * Calculate grid dimensions from k-point spacing, i.e. - * the maximum distance between adjacent points along a reciprocal axis. - * Note: just as the lattice vectors spacing is in cartesian (2pi / a) units by default - * @param {number} spacing - maximum Spacing between k-points - * @param {string} units - units of spacing parameter (default: 2pi / a) - */ - getDimensionsFromSpacing(spacing: number, units?: string): Vector3DSchema; - /** - * Calculate grid spacing as average of spacing along individual reciprocal axes. - * @param {number[]} dimensions - Array of dimensions - * @param {string} units - units of spacing parameter (default: 2pi / a) - * @return {number} - average grid spacing - */ - getSpacingFromDimensions(dimensions: number[], units?: string): number; -} -export {}; diff --git a/dist/js/lattice/reciprocal/lattice_reciprocal.js b/dist/js/lattice/reciprocal/lattice_reciprocal.js deleted file mode 100644 index 38886ba87..000000000 --- a/dist/js/lattice/reciprocal/lattice_reciprocal.js +++ /dev/null @@ -1,146 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ReciprocalLattice = void 0; -const constants_1 = require("@mat3ra/code/dist/js/constants"); -const utils_1 = require("@mat3ra/utils"); -const lodash_1 = __importDefault(require("lodash")); -const lattice_1 = require("../lattice"); -const paths_1 = require("./paths"); -const symmetry_points_1 = require("./symmetry_points"); -class ReciprocalLattice extends lattice_1.Lattice { - /** - * Get reciprocal vectors for the current Lattice in cartesian (2pi / a) units - * @return {Vector3DSchema[]} - */ - get reciprocalVectors() { - const vectors_ = this.vectors.vectorArrays; - const a = utils_1.Utils.math.vlen(vectors_[0]); - const divider = utils_1.Utils.math.multiply(vectors_[0], utils_1.Utils.math.cross(vectors_[1], vectors_[2])) / a; - return [ - utils_1.Utils.math.multiply(utils_1.Utils.math.cross(vectors_[1], vectors_[2]), 1 / divider), - utils_1.Utils.math.multiply(utils_1.Utils.math.cross(vectors_[2], vectors_[0]), 1 / divider), - utils_1.Utils.math.multiply(utils_1.Utils.math.cross(vectors_[0], vectors_[1]), 1 / divider), - ]; - } - /** - * Norms of reciprocal vectors. - */ - get reciprocalVectorNorms() { - return this.reciprocalVectors.map((vec) => utils_1.Utils.math.norm(vec)); - } - /** - * Ratio of reciprocal vector norms scaled by the inverse of the largest component. - */ - get reciprocalVectorRatios() { - const norms = this.reciprocalVectorNorms; - const maxNorm = utils_1.Utils.math.max(...norms); - return norms.map((n) => n / maxNorm); - } - /** - * Get point (in crystal coordinates) in cartesian coordinates. - * @param {KPointCoordinates} point - point in 3D space - * @return {KPointCoordinates} - */ - getCartesianCoordinates(point) { - return utils_1.Utils.math.multiply(point, this.reciprocalVectors); - } - /** - * Get the list of high-symmetry points for the current lattice. - * @return {SymmetryPoint[]} - */ - get symmetryPoints() { - return (0, symmetry_points_1.symmetryPoints)(this); - } - /** - * Get the default path in reciprocal space for the current lattice. - * @return {Array<{point: string; steps: number}>} - */ - get defaultKpointPath() { - const pathsObj = paths_1.paths; - return pathsObj[this.typeExtended] || pathsObj[this.type] || []; - } - /** - * Find/mark the high symmetry points on a list with raw data and return the edited list. - * @param {KPointCoordinates[]} dataPoints - list of point coordinates - * @return {KPointPath} - */ - extractKpointPath(dataPoints = []) { - const kpointPath = []; - const symmPoints = this.symmetryPoints; - dataPoints.forEach((point, index) => { - const symmPoint = symmPoints.find((x) => { - return utils_1.Utils.math.vEqualWithTolerance(x.coordinates, point, 1e-4); - }); - if (symmPoint) { - kpointPath.push({ - point: symmPoint.point, - steps: index, - coordinates: symmPoint.coordinates, - }); - } - }); - return kpointPath; - } - /** - * Calculate grid dimension based on reciprocal lattice vectors. - * @param {number} nPoints - Total number of points - * @param {number} index - Index of reciprocal vector - * @return {number} - Grid dimension in direction of reciprocal vector - * @todo This could be moved to a separate KGrid class. - */ - calculateDimension(nPoints, index) { - const norms = this.reciprocalVectorNorms; - const [j, k] = [0, 1, 2].filter((i) => i !== index); // get indices of other two dimensions - const N = utils_1.Utils.math.cbrt((nPoints * norms[index] ** 2) / (norms[j] * norms[k])); - return utils_1.Utils.math.max(1, utils_1.Utils.math.ceil(N)); - } - /** - * Calculate grid dimensions from total number of k-points. - * @param {number} nKpoints - Total number of k-points. - * @return Grid dimensions - */ - getDimensionsFromPointsCount(nKpoints) { - const indices = [0, 1, 2]; - return indices.map((i) => this.calculateDimension(nKpoints, i)); - } - get conversionTable() { - const { a } = this; - return { - [constants_1.ATOMIC_COORD_UNITS.cartesian]: { - [constants_1.units.angstrom]: (2 * utils_1.Utils.math.PI) / a, - }, - [constants_1.units.angstrom]: { - [constants_1.ATOMIC_COORD_UNITS.cartesian]: a / (2 * utils_1.Utils.math.PI), - }, - }; - } - /** - * Calculate grid dimensions from k-point spacing, i.e. - * the maximum distance between adjacent points along a reciprocal axis. - * Note: just as the lattice vectors spacing is in cartesian (2pi / a) units by default - * @param {number} spacing - maximum Spacing between k-points - * @param {string} units - units of spacing parameter (default: 2pi / a) - */ - getDimensionsFromSpacing(spacing, units = constants_1.ATOMIC_COORD_UNITS.cartesian) { - const factor = this.conversionTable[units][constants_1.ATOMIC_COORD_UNITS.cartesian] || 1; - return this.reciprocalVectorNorms.map((norm) => { - return utils_1.Utils.math.max(1, utils_1.Utils.math.ceil(lodash_1.default.round(norm / (spacing * factor), 4))); - }); - } - /** - * Calculate grid spacing as average of spacing along individual reciprocal axes. - * @param {number[]} dimensions - Array of dimensions - * @param {string} units - units of spacing parameter (default: 2pi / a) - * @return {number} - average grid spacing - */ - getSpacingFromDimensions(dimensions, units = constants_1.ATOMIC_COORD_UNITS.cartesian) { - const factor = this.conversionTable[constants_1.ATOMIC_COORD_UNITS.cartesian][units] || 1; - const norms = this.reciprocalVectorNorms; - return (factor * - utils_1.Utils.math.mean(dimensions.map((dim, i) => norms[i] / utils_1.Utils.math.max(1, dim)))); - } -} -exports.ReciprocalLattice = ReciprocalLattice; diff --git a/dist/js/lattice/reciprocal/paths.d.ts b/dist/js/lattice/reciprocal/paths.d.ts deleted file mode 100644 index a0aa8ebed..000000000 --- a/dist/js/lattice/reciprocal/paths.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -interface KPointStep { - point: string; - steps: number; -} -interface PathsType { - [key: string]: KPointStep[]; -} -export declare const paths: PathsType; -export {}; diff --git a/dist/js/lattice/reciprocal/paths.js b/dist/js/lattice/reciprocal/paths.js deleted file mode 100644 index 713595fa1..000000000 --- a/dist/js/lattice/reciprocal/paths.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.paths = void 0; -/** - * Default k-point paths according to: - * [AFLOW](https://arxiv.org/abs/1004.2974) methodology. - * Paths are split in parts for clarity. - * - * Raw segment data is stored in data/reciprocal_paths.json (shared with Python). - */ -const reciprocal_paths_json_1 = __importDefault(require("../../data/reciprocal_paths.json")); -// Export a processed version of the paths -exports.paths = (() => { - const result = {}; - Object.entries(reciprocal_paths_json_1.default).forEach(([key, pathSegments]) => { - // Flatten arrays of path segments into a single array - const flattenedPath = pathSegments.reduce((acc, segment) => [...acc, ...segment], []); - // Convert to KPointStep array - // TODO: calculate number of steps based on distance in k-space - result[key] = flattenedPath.map((point) => ({ - point, - steps: 10, - })); - }); - return result; -})(); diff --git a/dist/js/lattice/reciprocal/symmetry_points.d.ts b/dist/js/lattice/reciprocal/symmetry_points.d.ts deleted file mode 100644 index b4ea34fba..000000000 --- a/dist/js/lattice/reciprocal/symmetry_points.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Lattice } from "../lattice"; -/** - * Returns a list of symmetry points for the specified lattice. - */ -export declare function symmetryPoints(lattice: Lattice): { - point: string; - coordinates: number[]; -}[]; diff --git a/dist/js/lattice/reciprocal/symmetry_points.js b/dist/js/lattice/reciprocal/symmetry_points.js deleted file mode 100644 index f51eb5b75..000000000 --- a/dist/js/lattice/reciprocal/symmetry_points.js +++ /dev/null @@ -1,865 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.symmetryPoints = symmetryPoints; -const POINTS = { - CUB: () => { - return [ - { - point: "R", - coordinates: [0.5, 0.5, 0.5], - }, - { - point: "X", - coordinates: [0.0, 0.5, 0.0], - }, - { - point: "M", - coordinates: [0.5, 0.5, 0.0], - }, - ]; - }, - FCC: () => { - return [ - { - point: "K", - coordinates: [3 / 8, 3 / 8, 3 / 4], - }, - { - point: "L", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "U", - coordinates: [5 / 8, 1 / 4, 5 / 8], - }, - { - point: "W", - coordinates: [1 / 2, 1 / 4, 3 / 4], - }, - { - point: "X", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - ]; - }, - BCC: () => { - return [ - { - point: "H", - coordinates: [1 / 2, -1 / 2, 1 / 2], - }, - { - point: "P", - coordinates: [1 / 4, 1 / 4, 1 / 4], - }, - { - point: "N", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - }, - TET: () => { - return [ - { - point: "A", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "M", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "R", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "X", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - }, - BCT: ({ a, c }) => { - let n; - if (c < a) { - // BCT-1 - n = (1 + (c * c) / (a * a)) / 4; - return [ - { - point: "M", - coordinates: [-1 / 2, 1 / 2, 1 / 2], - }, - { - point: "N", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "P", - coordinates: [1 / 4, 1 / 4, 1 / 4], - }, - { - point: "X", - coordinates: [0.0, 0.0, 1 / 2], - }, - { - point: "Z", - coordinates: [n, n, -n], - }, - { - point: "Z1", - coordinates: [-n, 1 - n, n], - }, - ]; - } - // BCT-2 - n = (1 + (a * a) / (c * c)) / 4; - const e = (a * a) / (2 * c * c); - return [ - { - point: "N", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "P", - coordinates: [1 / 4, 1 / 4, 1 / 4], - }, - { - point: "∑", - coordinates: [-n, n, n], - }, - { - point: "∑1", - coordinates: [n, 1 - n, -n], - }, - { - point: "X", - coordinates: [0, 0, 1 / 2], - }, - { - point: "Y", - coordinates: [-e, e, 1 / 2], - }, - { - point: "Y1", - coordinates: [1 / 2, 1 / 2, -e], - }, - { - point: "Z", - coordinates: [1 / 2, 1 / 2, -1 / 2], - }, - ]; - }, - ORC: () => { - return [ - { - point: "R", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "S", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "T", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "U", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "X", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "Y", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - }, - ORCF: ({ a, b, c }) => { - let n; - if (1 / (a * a) >= 1 / (b * b) + 1 / (c * c)) { - // ORCF-1,3 - n = (1 + (a * a) / (b * b) + (a * a) / (c * c)) / 4; - const e = (1 + (a * a) / (b * b) - (a * a) / (c * c)) / 4; - return [ - { - point: "A", - coordinates: [1 / 2, 1 / 2 + e, e], - }, - { - point: "A1", - coordinates: [0.0, 1 / 2 - e, 1 - e], - }, - { - point: "L", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "T", - coordinates: [1.0, 1 / 2, 1 / 2], - }, - { - point: "X", - coordinates: [0.0, n, n], - }, - { - point: "X1", - coordinates: [1.0, 1 - n, 1 - n], - }, - { - point: "Y", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "Z", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - ]; - } - // ORCF-2 - n = (1 + (a * a) / (b * b) - (a * a) / (c * c)) / 4; - const f = (1 + (c * c) / (b * b) - (c * c) / (a * a)) / 4; - const d = (1 + (b * b) / (a * a) - (b * b) / (c * c)) / 4; - return [ - { - point: "C", - coordinates: [1 / 2, 1 / 2 - n, 1 - n], - }, - { - point: "C1", - coordinates: [0.0, 1 / 2 + n, n], - }, - { - point: "D", - coordinates: [1 / 2 - d, 1 / 2, 1 - d], - }, - { - point: "D1", - coordinates: [1 / 2 + d, 1 / 2, d], - }, - { - point: "L", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "H", - coordinates: [1 - f, 1 / 2 - f, 1 / 2], - }, - { - point: "H1", - coordinates: [f, 1 / 2 + f, 1 / 2], - }, - { - point: "X", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "Y", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "Z", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - ]; - }, - ORCI: ({ a, b, c }) => { - const n = (1 + (a * a) / (c * c)) / 4; - const e = (1 + (b * b) / (c * c)) / 4; - const d = (b * b - a * a) / (4 * c * c); - const m = (b * b + a * a) / (4 * c * c); - return [ - { - point: "L", - coordinates: [-m, m, 1 / 2 - d], - }, - { - point: "L1", - coordinates: [m, -m, 1 / 2 + d], - }, - { - point: "L2", - coordinates: [1 / 2 - d, 1 / 2 + d, -m], - }, - { - point: "R", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "S", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "T", - coordinates: [0.0, 0.0, 1 / 2], - }, - { - point: "W", - coordinates: [1 / 4, 1 / 4, 1 / 4], - }, - { - point: "X", - coordinates: [-e, e, e], - }, - { - point: "X1", - coordinates: [e, 1 - e, -e], - }, - { - point: "Y", - coordinates: [n, -n, n], - }, - { - point: "Y1", - coordinates: [1 - n, n, -n], - }, - { - point: "Z", - coordinates: [1 / 2, 1 / 2, -1 / 2], - }, - ]; - }, - ORCC: ({ a, b }) => { - const e = (1 + (a * a) / (b * b)) / 4; - return [ - { - point: "A", - coordinates: [e, e, 1 / 2], - }, - { - point: "A1", - coordinates: [-e, 1 - e, 1 / 2], - }, - { - point: "R", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "S", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "T", - coordinates: [-1 / 2, 1 / 2, 1 / 2], - }, - { - point: "X", - coordinates: [e, e, 0.0], - }, - { - point: "X1", - coordinates: [-e, 1 - e, 0.0], - }, - { - point: "Y", - coordinates: [-1 / 2, 1 / 2, 0.0], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - }, - HEX: () => { - return [ - { - point: "A", - coordinates: [0.0, 0.0, 1 / 2], - }, - { - point: "H", - coordinates: [1 / 3, 1 / 3, 1 / 2], - }, - { - point: "K", - coordinates: [1 / 3, 1 / 3, 0.0], - }, - { - point: "L", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "M", - coordinates: [1 / 2, 0.0, 0.0], - }, - ]; - }, - RHL: ({ alpha }) => { - let n, v; - const cosAlpha = Math.cos((alpha / 180) * Math.PI); - if (cosAlpha > 0) { - // RHL-1 - n = (1 + 4 * cosAlpha) / (2 + 4 * cosAlpha); - v = 3 / 4 - n / 2; - return [ - { - point: "B", - coordinates: [n, 1 / 2, 1 - n], - }, - { - point: "B1", - coordinates: [1 / 2, 1 - n, n - 1], - }, - { - point: "F", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "L", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "L1", - coordinates: [0.0, 0.0, -1 / 2], - }, - { - point: "P", - coordinates: [n, v, v], - }, - { - point: "P1", - coordinates: [1 - v, 1 - v, 1 - n], - }, - { - point: "P2", - coordinates: [v, v, n - 1], - }, - { - point: "Q", - coordinates: [1 - v, v, 0.0], - }, - { - point: "X", - coordinates: [v, 0.0, -v], - }, - { - point: "Z", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - ]; - } - // RHL-2 - n = ((1 / 2) * (1 + cosAlpha)) / (1 - cosAlpha); - v = 3 / 4 - n / 2; - return [ - { - point: "F", - coordinates: [1 / 2, -1 / 2, 0.0], - }, - { - point: "L", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "P", - coordinates: [1 - v, -v, 1 - v], - }, - { - point: "P1", - coordinates: [v, v - 1, v - 1], - }, - { - point: "Q", - coordinates: [n, n, n], - }, - { - point: "Q1", - coordinates: [1 - n, -n, -n], - }, - { - point: "Z", - coordinates: [1 / 2, -1 / 2, 1 / 2], - }, - ]; - }, - MCL: ({ b, c, alpha }) => { - const cosAlpha = Math.cos((alpha / 180) * Math.PI); - const n = ((1 / 2) * (1 - (b * cosAlpha) / c)) / (1 - cosAlpha * cosAlpha); - const v = 1 / 2 - (n * c * cosAlpha) / b; - return [ - { - point: "A", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "C", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "D", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "D1", - coordinates: [1 / 2, 0.0, -1 / 2], - }, - { - point: "E", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "H", - coordinates: [0.0, n, 1 - v], - }, - { - point: "H1", - coordinates: [0.0, 1 - n, v], - }, - { - point: "H2", - coordinates: [0.0, n, -v], - }, - { - point: "M", - coordinates: [1 / 2, n, 1 - v], - }, - { - point: "M1", - coordinates: [1 / 2, 1 - n, v], - }, - { - point: "M2", - coordinates: [1 / 2, n, -v], - }, - { - point: "X", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "Y", - coordinates: [0.0, 0.0, 1 / 2], - }, - { - point: "Y1", - coordinates: [0.0, 0.0, -1 / 2], - }, - { - point: "Z", - coordinates: [1 / 2, 0.0, 0.0], - }, - ]; - }, - MCLC: ({ a, b, c, alpha, gamma }) => { - const cosAlpha = Math.cos((alpha / 180) * Math.PI); - let e, n, p, f, m, d, v; - if (gamma >= 90) { - // MCLC-1,2 - e = (2 - (b * cosAlpha) / c) / (4 * (1 - cosAlpha * cosAlpha)); - n = 1 / 2 + (2 * e * c * cosAlpha) / b; - p = 3 / 4 - (a * a) / (4 * b * b * (1 - cosAlpha * cosAlpha)); - f = p + ((3 / 4 - p) * cosAlpha * b) / c; - return [ - { - point: "N", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "N1", - coordinates: [0.0, -1 / 2, 0.0], - }, - { - point: "F", - coordinates: [1 - e, 1 - e, 1 - n], - }, - { - point: "F1", - coordinates: [e, e, n], - }, - { - point: "F2", - coordinates: [-e, -e, 1 - n], - }, - { - point: "F3", - coordinates: [1 - e, -e, 1 - n], - }, - { - point: "I", - coordinates: [f, 1 - f, 1 / 2], - }, - { - point: "I1", - coordinates: [1 - f, f - 1, 1 / 2], - }, - { - point: "L", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "M", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "X", - coordinates: [1 - p, p - 1, 0.0], - }, - { - point: "X1", - coordinates: [p, 1 - p, 0.0], - }, - { - point: "X2", - coordinates: [p - 1, -p, 0.0], - }, - { - point: "Y", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "Y1", - coordinates: [-1 / 2, -1 / 2, 0.0], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - } - if ((b / c) * cosAlpha + ((b * b) / (a * a)) * (1 - cosAlpha * cosAlpha) <= 1) { - // MCLC-3,4 - m = (1 + (b * b) / (a * a)) / 4; - d = (b * c * cosAlpha) / (2 * a * a); - e = m - 1 / 4 + (1 - (b * cosAlpha) / c) / (4 * (1 - cosAlpha * cosAlpha)); - n = 1 / 2 + (2 * e * c * cosAlpha) / b; - f = 1 + e - 2 * m; - p = n - 2 * d; - return [ - { - point: "N", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "N1", - coordinates: [0.0, -1 / 2, 0.0], - }, - { - point: "F", - coordinates: [1 - f, 1 - f, 1 - p], - }, - { - point: "F1", - coordinates: [f, f - 1, p], - }, - { - point: "F2", - coordinates: [1 - f, -f, 1 - p], - }, - { - point: "H", - coordinates: [e, e, n], - }, - { - point: "H1", - coordinates: [1 - e, -e, 1 - n], - }, - { - point: "H2", - coordinates: [-e, -e, 1 - n], - }, - { - point: "I", - coordinates: [1 / 2, -1 / 2, 1 / 2], - }, - { - point: "M", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "X", - coordinates: [1 / 2, -1 / 2, 0.0], - }, - { - point: "Y", - coordinates: [m, m, d], - }, - { - point: "Y1", - coordinates: [1 - m, -m, -d], - }, - { - point: "Y2", - coordinates: [-m, -m, -d], - }, - { - point: "Y3", - coordinates: [m, m - 1, d], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - } - // MCLC-5 - e = (1 / 4) * ((b * b) / (a * a) + (1 - (b * cosAlpha) / c) / (1 - cosAlpha * cosAlpha)); - // @ts-ignore - m = n / 2 + (b * b) / (a * a) / 4 - (b * c * cosAlpha) / (2 * a * a); - // eslint-disable-next-line max-len - const w = // @ts-ignore - ((4 * v - 1 - (b * b * (1 - cosAlpha * cosAlpha)) / (a * a)) * c) / (2 * b * cosAlpha); - n = 1 / 2 + (2 * e * c * cosAlpha) / b; - d = ((e * c) / b) * cosAlpha + w / 2 - 1 / 4; - v = 1 + e - 2 * m; - const r = 1 - (e * a * a) / (b * b); - return [ - { - point: "N", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "N1", - coordinates: [0.0, -1 / 2, 0.0], - }, - { - point: "F", - coordinates: [v, v, w], - }, - { - point: "F1", - coordinates: [1 - v, 1 - v, 1 - w], - }, - { - point: "F2", - coordinates: [v, v - 1, w], - }, - { - point: "H", - coordinates: [e, e, n], - }, - { - point: "H1", - coordinates: [1 - e, -e, 1 - n], - }, - { - point: "H2", - coordinates: [-e, -e, 1 - n], - }, - { - point: "I", - coordinates: [r, 1 - r, 1 / 2], - }, - { - point: "I1", - coordinates: [1 - r, r - 1, 1 / 2], - }, - { - point: "L", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "M", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "X", - coordinates: [1 / 2, -1 / 2, 0.0], - }, - { - point: "Y", - coordinates: [m, m, d], - }, - { - point: "Y1", - coordinates: [1 - m, -m, -d], - }, - { - point: "Y2", - coordinates: [-m, -m, -d], - }, - { - point: "Y3", - coordinates: [m, m - 1, d], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - }, - TRI: ({ alpha, beta, gamma }) => { - if (alpha > 90 && beta > 90 && gamma >= 90) { - // TRI-1a,2a - return [ - { - point: "L", - coordinates: [1 / 2, 1 / 2, 0.0], - }, - { - point: "M", - coordinates: [0.0, 1 / 2, 1 / 2], - }, - { - point: "N", - coordinates: [1 / 2, 0.0, 1 / 2], - }, - { - point: "R", - coordinates: [1 / 2, 1 / 2, 1 / 2], - }, - { - point: "X", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "Y", - coordinates: [0.0, 1 / 2, 0.0], - }, - { - point: "Z", - coordinates: [0.0, 0.0, 1 / 2], - }, - ]; - } - // TRI-1b,2b - return [ - { - point: "L", - coordinates: [1 / 2, -1 / 2, 0.0], - }, - { - point: "M", - coordinates: [0.0, 0.0, 1 / 2], - }, - { - point: "N", - coordinates: [-1 / 2, -1 / 2, 1 / 2], - }, - { - point: "R", - coordinates: [0.0, -1 / 2, 1 / 2], - }, - { - point: "X", - coordinates: [0.0, -1 / 2, 0.0], - }, - { - point: "Y", - coordinates: [1 / 2, 0.0, 0.0], - }, - { - point: "Z", - coordinates: [-1 / 2, 0.0, 1 / 2], - }, - ]; - }, -}; -/** - * Returns a list of symmetry points for the specified lattice. - */ -function symmetryPoints(lattice) { - return [ - { - point: "Γ", - coordinates: [0.0, 0.0, 0.0], - }, - ].concat(POINTS[lattice.type](lattice) || []); -} diff --git a/dist/js/lattice/unit_cell.d.ts b/dist/js/lattice/unit_cell.d.ts deleted file mode 100644 index 415236460..000000000 --- a/dist/js/lattice/unit_cell.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -export type UnitCellProps = [ - number, - number, - number, - number, - number, - number, - number, - number, - number, - string -]; -export declare class UnitCell { - ax: number; - ay: number; - az: number; - bx: number; - by: number; - bz: number; - cx: number; - cy: number; - cz: number; - units: string; - constructor([ax, ay, az, bx, by, bz, cx, cy, cz, units]: UnitCellProps); - vectorA(): Vector3DSchema; - vectorB(): Vector3DSchema; - vectorC(): Vector3DSchema; - axes(): [Vector3DSchema, Vector3DSchema, Vector3DSchema]; -} diff --git a/dist/js/lattice/unit_cell.js b/dist/js/lattice/unit_cell.js deleted file mode 100644 index 085a45a0e..000000000 --- a/dist/js/lattice/unit_cell.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UnitCell = void 0; -// TODO: refactor and remove the need for UnitCell -class UnitCell { - constructor([ax, ay, az, bx, by, bz, cx, cy, cz, units]) { - this.ax = ax; - this.ay = ay; - this.az = az; - this.bx = bx; - this.by = by; - this.bz = bz; - this.cx = cx; - this.cy = cy; - this.cz = cz; - this.units = units; - } - vectorA() { - return [this.ax, this.ay, this.az]; - } - vectorB() { - return [this.bx, this.by, this.bz]; - } - vectorC() { - return [this.cx, this.cy, this.cz]; - } - axes() { - return [this.vectorA(), this.vectorB(), this.vectorC()]; - } -} -exports.UnitCell = UnitCell; diff --git a/dist/js/made.d.ts b/dist/js/made.d.ts deleted file mode 100644 index 4039dcae8..000000000 --- a/dist/js/made.d.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { Basis } from "./basis/basis"; -import { Cell } from "./cell/cell"; -import { ATOMIC_COORD_UNITS, coefficients, tolerance, units } from "./constants"; -import { AtomicConstraints } from "./constraints/constraints"; -import { defaultNonPeriodicMinimumLatticeSize, diatomicLatticePaddingFactor, Lattice, molecularLatticePaddingFactor } from "./lattice/lattice"; -import { DEFAULT_LATTICE_UNITS, LATTICE_TYPE_CONFIGS } from "./lattice/lattice_types"; -import { ReciprocalLattice } from "./lattice/reciprocal/lattice_reciprocal"; -import { UnitCell } from "./lattice/unit_cell"; -import Material, { defaultMaterialConfig } from "./Material"; -import parsers from "./parsers/parsers"; -import tools from "./tools/index"; -export declare const Made: { - coefficients: { - EV_TO_RY: number; - BOHR_TO_ANGSTROM: number; - ANGSTROM_TO_BOHR: number; - EV_A_TO_RY_BOHR: number; - }; - tolerance: { - length: number; - lengthAngstrom: number; - pointsDistance: number; - }; - units: { - bohr: string; - angstrom: string; - degree: string; - radian: string; - alat: string; - }; - ATOMIC_COORD_UNITS: { - crystal: string; - cartesian: string; - }; - Material: typeof Material; - defaultMaterialConfig: import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema; - Lattice: typeof Lattice; - Cell: typeof Cell; - UnitCell: typeof UnitCell; - defaultNonPeriodicMinimumLatticeSize: number; - diatomicLatticePaddingFactor: number; - molecularLatticePaddingFactor: number; - ReciprocalLattice: typeof ReciprocalLattice; - Basis: typeof Basis; - AtomicConstraints: typeof AtomicConstraints; - parsers: { - xyz: { - validate: typeof import("./parsers/xyz").validate; - fromMaterial: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema, fractional?: boolean) => string; - toBasisConfig: (txt: string, units?: string, cell?: Cell) => import("./basis/constrained_basis").ConstrainedBasisConfig; - fromBasis: (basisClsInstance: import("./basis/constrained_basis").ConstrainedBasis, coordinatePrintFormat: string) => string; - CombinatorialBasis: typeof import("./parsers/xyz_combinatorial_basis").CombinatorialBasis; - }; - poscar: { - isPoscar: (text: string) => boolean; - toPoscar: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema, omitConstraints?: boolean) => string; - fromPoscar: (fileContent: string) => import("./Material").MaterialConfig; - atomicConstraintsCharFromBool: (bool: boolean) => string; - atomsCount: typeof import("./parsers/poscar").atomsCount; - }; - cif: { - parseMeta: (txt: string) => import("./parsers/cif").Meta; - }; - espresso: { - toEspressoFormat: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema) => string; - }; - nativeFormatParsers: { - detectFormat: (text: string) => "json" | "poscar" | "unknown"; - convertFromNativeFormat: (text: string) => import("./Material").MaterialConfig; - }; - }; - tools: { - surface: { - generateConfig: (material: Material, millerIndices: import("@mat3ra/esse/dist/js/types").Coordinate3DSchema, numberOfLayers?: number, vx?: number, vy?: number) => import("./tools/surface").SlabConfigSchema; - }; - supercell: { - generateConfig: (material: Material, supercellMatrix: import("@mat3ra/esse/dist/js/types").Matrix3X3Schema) => { - name: string; - basis: import("./basis/basis").BasisConfig & import("@mat3ra/esse/dist/js/types").BaseInMemoryEntitySchema; - lattice: import("@mat3ra/esse/dist/js/types").LatticeSchema; - }; - generateNewBasisWithinSupercell: (basis: Basis | import("./basis/constrained_basis").ConstrainedBasis, cell: Cell, supercell: Cell, supercellMatrix: import("@mat3ra/esse/dist/js/types").Matrix3X3Schema) => Basis; - }; - material: { - scaleOneLatticeVector: (material: Material, key?: "a" | "b" | "c", factor?: number) => void; - scaleLatticeToMakeNonPeriodic: (material: Material) => void; - translateAtomsToCenter: (material: Material) => void; - }; - basis: { - repeat: (basis: Basis, repetitions: number[]) => Basis; - interpolate: (initialBasis: Basis, finalBasis: Basis, numberOfSteps?: number) => Basis[]; - }; - }; - LATTICE_TYPE_CONFIGS: import("./lattice/lattice_types").LatticeTypeConfig[]; - DEFAULT_LATTICE_UNITS: { - length: { - angstrom: string; - }; - angle: { - degree: string; - }; - }; -}; -export { coefficients, tolerance, units, ATOMIC_COORD_UNITS, Material, defaultMaterialConfig, Lattice, Cell, UnitCell, defaultNonPeriodicMinimumLatticeSize, diatomicLatticePaddingFactor, molecularLatticePaddingFactor, ReciprocalLattice, Basis, AtomicConstraints, parsers, tools, LATTICE_TYPE_CONFIGS, DEFAULT_LATTICE_UNITS, }; diff --git a/dist/js/made.js b/dist/js/made.js deleted file mode 100644 index e87eabdd2..000000000 --- a/dist/js/made.js +++ /dev/null @@ -1,90 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_LATTICE_UNITS = exports.LATTICE_TYPE_CONFIGS = exports.tools = exports.parsers = exports.AtomicConstraints = exports.Basis = exports.ReciprocalLattice = exports.molecularLatticePaddingFactor = exports.diatomicLatticePaddingFactor = exports.defaultNonPeriodicMinimumLatticeSize = exports.UnitCell = exports.Cell = exports.Lattice = exports.defaultMaterialConfig = exports.Material = exports.ATOMIC_COORD_UNITS = exports.units = exports.tolerance = exports.coefficients = exports.Made = void 0; -const basis_1 = require("./basis/basis"); -Object.defineProperty(exports, "Basis", { enumerable: true, get: function () { return basis_1.Basis; } }); -const cell_1 = require("./cell/cell"); -Object.defineProperty(exports, "Cell", { enumerable: true, get: function () { return cell_1.Cell; } }); -const constants_1 = require("./constants"); -Object.defineProperty(exports, "ATOMIC_COORD_UNITS", { enumerable: true, get: function () { return constants_1.ATOMIC_COORD_UNITS; } }); -Object.defineProperty(exports, "coefficients", { enumerable: true, get: function () { return constants_1.coefficients; } }); -Object.defineProperty(exports, "tolerance", { enumerable: true, get: function () { return constants_1.tolerance; } }); -Object.defineProperty(exports, "units", { enumerable: true, get: function () { return constants_1.units; } }); -const constraints_1 = require("./constraints/constraints"); -Object.defineProperty(exports, "AtomicConstraints", { enumerable: true, get: function () { return constraints_1.AtomicConstraints; } }); -const lattice_1 = require("./lattice/lattice"); -Object.defineProperty(exports, "defaultNonPeriodicMinimumLatticeSize", { enumerable: true, get: function () { return lattice_1.defaultNonPeriodicMinimumLatticeSize; } }); -Object.defineProperty(exports, "diatomicLatticePaddingFactor", { enumerable: true, get: function () { return lattice_1.diatomicLatticePaddingFactor; } }); -Object.defineProperty(exports, "Lattice", { enumerable: true, get: function () { return lattice_1.Lattice; } }); -Object.defineProperty(exports, "molecularLatticePaddingFactor", { enumerable: true, get: function () { return lattice_1.molecularLatticePaddingFactor; } }); -const lattice_types_1 = require("./lattice/lattice_types"); -Object.defineProperty(exports, "DEFAULT_LATTICE_UNITS", { enumerable: true, get: function () { return lattice_types_1.DEFAULT_LATTICE_UNITS; } }); -Object.defineProperty(exports, "LATTICE_TYPE_CONFIGS", { enumerable: true, get: function () { return lattice_types_1.LATTICE_TYPE_CONFIGS; } }); -const lattice_reciprocal_1 = require("./lattice/reciprocal/lattice_reciprocal"); -Object.defineProperty(exports, "ReciprocalLattice", { enumerable: true, get: function () { return lattice_reciprocal_1.ReciprocalLattice; } }); -const unit_cell_1 = require("./lattice/unit_cell"); -Object.defineProperty(exports, "UnitCell", { enumerable: true, get: function () { return unit_cell_1.UnitCell; } }); -const Material_1 = __importStar(require("./Material")); -exports.Material = Material_1.default; -Object.defineProperty(exports, "defaultMaterialConfig", { enumerable: true, get: function () { return Material_1.defaultMaterialConfig; } }); -const parsers_1 = __importDefault(require("./parsers/parsers")); -exports.parsers = parsers_1.default; -const index_1 = __importDefault(require("./tools/index")); -exports.tools = index_1.default; -exports.Made = { - coefficients: constants_1.coefficients, - tolerance: constants_1.tolerance, - units: constants_1.units, - ATOMIC_COORD_UNITS: constants_1.ATOMIC_COORD_UNITS, - Material: Material_1.default, - defaultMaterialConfig: Material_1.defaultMaterialConfig, - Lattice: lattice_1.Lattice, - Cell: cell_1.Cell, - UnitCell: unit_cell_1.UnitCell, - defaultNonPeriodicMinimumLatticeSize: lattice_1.defaultNonPeriodicMinimumLatticeSize, - diatomicLatticePaddingFactor: lattice_1.diatomicLatticePaddingFactor, - molecularLatticePaddingFactor: lattice_1.molecularLatticePaddingFactor, - ReciprocalLattice: lattice_reciprocal_1.ReciprocalLattice, - Basis: basis_1.Basis, - AtomicConstraints: constraints_1.AtomicConstraints, - parsers: parsers_1.default, - tools: index_1.default, - LATTICE_TYPE_CONFIGS: lattice_types_1.LATTICE_TYPE_CONFIGS, - DEFAULT_LATTICE_UNITS: lattice_types_1.DEFAULT_LATTICE_UNITS, -}; diff --git a/dist/js/parsers/cif.d.ts b/dist/js/parsers/cif.d.ts deleted file mode 100644 index 5f325f070..000000000 --- a/dist/js/parsers/cif.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export interface Meta { - icsdId?: number; -} -/** - * Extracts meta information from a CIF file - * @param txt - CIF file text. - */ -declare function parseMeta(txt: string): Meta; -declare const _default: { - parseMeta: typeof parseMeta; -}; -export default _default; diff --git a/dist/js/parsers/cif.js b/dist/js/parsers/cif.js deleted file mode 100644 index c449dd9d2..000000000 --- a/dist/js/parsers/cif.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Extracts meta information from a CIF file - * @param txt - CIF file text. - */ -function parseMeta(txt) { - const REGEX = { - ICSD_ID: /_database_code_ICSD\s+(\d+)/, - }; - const meta = {}; - const groups = txt.match(REGEX.ICSD_ID); - if (groups) { - meta.icsdId = Number(groups[1]); - } - return meta; -} -exports.default = { - parseMeta, -}; diff --git a/dist/js/parsers/errors.d.ts b/dist/js/parsers/errors.d.ts deleted file mode 100644 index 41d913f09..000000000 --- a/dist/js/parsers/errors.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export declare class InvalidLineError extends Error { - constructor(num: number, content: string); -} diff --git a/dist/js/parsers/errors.js b/dist/js/parsers/errors.js deleted file mode 100644 index f145d8305..000000000 --- a/dist/js/parsers/errors.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InvalidLineError = void 0; -class InvalidLineError extends Error { - constructor(num, content) { - super(`Invalid line: ${num}`); - console.log(`Invalid line: ${num}, content: ${content}`); - } -} -exports.InvalidLineError = InvalidLineError; diff --git a/dist/js/parsers/espresso.d.ts b/dist/js/parsers/espresso.d.ts deleted file mode 100644 index 4cbbe4651..000000000 --- a/dist/js/parsers/espresso.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MaterialEnhancedSchema, MaterialSchema } from "@mat3ra/esse/dist/js/types"; -/** - * Construct textual representation of a materialOrConfig according to Quantum ESPRESSO pw.x input format. - */ -declare function toEspressoFormat(materialOrConfig: MaterialSchema | MaterialEnhancedSchema): string; -declare const _default: { - toEspressoFormat: typeof toEspressoFormat; -}; -export default _default; diff --git a/dist/js/parsers/espresso.js b/dist/js/parsers/espresso.js deleted file mode 100644 index 6fe12530c..000000000 --- a/dist/js/parsers/espresso.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const lodash_1 = require("lodash"); -const underscore_string_1 = __importDefault(require("underscore.string")); -const lattice_1 = require("../lattice/lattice"); -const xyz_1 = __importDefault(require("./xyz")); -/** - * Construct textual representation of a materialOrConfig according to Quantum ESPRESSO pw.x input format. - */ -function toEspressoFormat(materialOrConfig) { - const l = new lattice_1.Lattice(materialOrConfig.lattice); - const vectors = l.vectorArrays; - const vectorsAsString = (0, lodash_1.map)(vectors, (v) => { - return `${underscore_string_1.default.sprintf("%14.9f", v[0])}\t${underscore_string_1.default.sprintf("%14.9f", v[1])}\t${underscore_string_1.default.sprintf("%14.9f", v[2])}`; - }).join("\n"); - return underscore_string_1.default.sprintf("CELL_PARAMETERS (angstroms)\n%s\n\nATOMIC_POSITIONS (crystal)\n%s", vectorsAsString, xyz_1.default.fromMaterial(materialOrConfig)); -} -exports.default = { - toEspressoFormat, -}; diff --git a/dist/js/parsers/native_format_parsers.d.ts b/dist/js/parsers/native_format_parsers.d.ts deleted file mode 100644 index 8c4f32c21..000000000 --- a/dist/js/parsers/native_format_parsers.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { MaterialConfig } from "../Material"; -/** - * @summary Detects the format of the input string - * @throws If the input string is unknown format - * @param text input string to detect format - * @returns Format of the input string - */ -declare function detectFormat(text: string): "json" | "poscar" | "unknown"; -/** - * @summary Function to handle conversion from native formats - * @param text - input string to detect format and convert - * @throws If the input string is of unknown format - * @return Material config - */ -declare function convertFromNativeFormat(text: string): MaterialConfig; -declare const _default: { - detectFormat: typeof detectFormat; - convertFromNativeFormat: typeof convertFromNativeFormat; -}; -export default _default; diff --git a/dist/js/parsers/native_format_parsers.js b/dist/js/parsers/native_format_parsers.js deleted file mode 100644 index 7907e0ddc..000000000 --- a/dist/js/parsers/native_format_parsers.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const poscar_1 = __importDefault(require("./poscar")); -const NATIVE_FORMAT = { - JSON: "json", - POSCAR: "poscar", - CIF: "cif", - PWX: "pwx", - XYZ: "xyz", - UNKNOWN: "unknown", -}; -/** - * @summary Detects the format of the input string - * @throws If the input string is unknown format - * @param text input string to detect format - * @returns Format of the input string - */ -function detectFormat(text) { - const jsonRegex = /^\s*\{/; - if (jsonRegex.test(text)) - return NATIVE_FORMAT.JSON; - if (poscar_1.default.isPoscar(text)) - return NATIVE_FORMAT.POSCAR; - return NATIVE_FORMAT.UNKNOWN; -} -/** - * @summary Function to handle conversion from native formats - * @param text - input string to detect format and convert - * @throws If the input string is of unknown format - * @return Material config - */ -function convertFromNativeFormat(text) { - const format = detectFormat(text); - switch (format) { - case NATIVE_FORMAT.JSON: - return JSON.parse(text); - case NATIVE_FORMAT.POSCAR: - return poscar_1.default.fromPoscar(text); - case NATIVE_FORMAT.UNKNOWN: - throw new Error(`Unknown format`); - // TODO: add more formats - default: - throw new Error(`Unsupported format: ${format}`); - } -} -exports.default = { - detectFormat, - convertFromNativeFormat, -}; diff --git a/dist/js/parsers/parsers.d.ts b/dist/js/parsers/parsers.d.ts deleted file mode 100644 index 2f2b950dd..000000000 --- a/dist/js/parsers/parsers.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -declare const _default: { - xyz: { - validate: typeof import("./xyz").validate; - fromMaterial: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema, fractional?: boolean) => string; - toBasisConfig: (txt: string, units?: string, cell?: import("../made").Cell) => import("../basis/constrained_basis").ConstrainedBasisConfig; - fromBasis: (basisClsInstance: import("../basis/constrained_basis").ConstrainedBasis, coordinatePrintFormat: string) => string; - CombinatorialBasis: typeof import("./xyz_combinatorial_basis").CombinatorialBasis; - }; - poscar: { - isPoscar: (text: string) => boolean; - toPoscar: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema, omitConstraints?: boolean) => string; - fromPoscar: (fileContent: string) => import("../Material").MaterialConfig; - atomicConstraintsCharFromBool: (bool: boolean) => string; - atomsCount: typeof import("./poscar").atomsCount; - }; - cif: { - parseMeta: (txt: string) => import("./cif").Meta; - }; - espresso: { - toEspressoFormat: (materialOrConfig: import("@mat3ra/esse/dist/js/types").MaterialSchema | import("@mat3ra/esse/dist/js/types").MaterialEnhancedSchema) => string; - }; - nativeFormatParsers: { - detectFormat: (text: string) => "json" | "poscar" | "unknown"; - convertFromNativeFormat: (text: string) => import("../Material").MaterialConfig; - }; -}; -export default _default; diff --git a/dist/js/parsers/parsers.js b/dist/js/parsers/parsers.js deleted file mode 100644 index c75d3287e..000000000 --- a/dist/js/parsers/parsers.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const cif_1 = __importDefault(require("./cif")); -const espresso_1 = __importDefault(require("./espresso")); -const native_format_parsers_1 = __importDefault(require("./native_format_parsers")); -const poscar_1 = __importDefault(require("./poscar")); -const xyz_1 = __importDefault(require("./xyz")); -exports.default = { - xyz: xyz_1.default, - poscar: poscar_1.default, - cif: cif_1.default, - espresso: espresso_1.default, - nativeFormatParsers: native_format_parsers_1.default, -}; diff --git a/dist/js/parsers/poscar.d.ts b/dist/js/parsers/poscar.d.ts deleted file mode 100644 index d8aea805b..000000000 --- a/dist/js/parsers/poscar.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { MaterialEnhancedSchema, MaterialSchema } from "@mat3ra/esse/dist/js/types"; -import type { MaterialConfig } from "../Material"; -/** - * Obtain a textual representation of a material in POSCAR format. - * @param materialOrConfig - material class instance or config object. - * @param omitConstraints - whether to discard constraints when serializing. - */ -declare function toPoscar(materialOrConfig: MaterialSchema | MaterialEnhancedSchema, omitConstraints?: boolean): string; -/** - * @summary calculates the number of atoms in a poscar file based on the summation of the numbers in line 7 of the file. - * Poscar file formatting: https://www.vasp.at/wiki/index.php/POSCAR - */ -export declare function atomsCount(poscarFileContent: string): number; -/** - * Parses POSCAR file into a Material config object. - * @param fileContent - POSCAR file content. - * @return Material config. - */ -declare function fromPoscar(fileContent: string): MaterialConfig; -/** - * @summary Checks if a string has a POSCAR format (first 8 lines are read) - * @param text - string to check - */ -declare function isPoscar(text: string): boolean; -declare const _default: { - isPoscar: typeof isPoscar; - toPoscar: typeof toPoscar; - fromPoscar: typeof fromPoscar; - atomicConstraintsCharFromBool: (bool: boolean) => string; - atomsCount: typeof atomsCount; -}; -export default _default; diff --git a/dist/js/parsers/poscar.js b/dist/js/parsers/poscar.js deleted file mode 100644 index 4da79a2c8..000000000 --- a/dist/js/parsers/poscar.js +++ /dev/null @@ -1,184 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.atomsCount = atomsCount; -const utils_1 = require("@mat3ra/utils"); -const underscore_string_1 = __importDefault(require("underscore.string")); -const constrained_basis_1 = require("../basis/constrained_basis"); -const cell_1 = require("../cell/cell"); -const constants_1 = require("../constants"); -const lattice_1 = require("../lattice/lattice"); -const _print = (x, printFormat = "%14.9f") => underscore_string_1.default.sprintf(printFormat, utils_1.Utils.math.precise(x)); -const _latticeVectorsToString = (vectors) => vectors.map((v) => v.map((c) => _print(c)).join("\t")).join("\n"); -const atomicConstraintsCharFromBool = (bool) => (bool ? "T" : "F"); -/** - * Obtain a textual representation of a material in POSCAR format. - * @param materialOrConfig - material class instance or config object. - * @param omitConstraints - whether to discard constraints when serializing. - */ -function toPoscar(materialOrConfig, omitConstraints = false) { - const lattice = new lattice_1.Lattice(materialOrConfig.lattice); - const vectorsAsString = _latticeVectorsToString(lattice.vectorArrays); - const constraints = "constraints" in materialOrConfig.basis ? materialOrConfig.basis.constraints : []; - const basis = new constrained_basis_1.ConstrainedBasis({ - ...materialOrConfig.basis, - cell: cell_1.Cell.fromVectorsArray(lattice.vectorArrays), - constraints: omitConstraints ? [] : constraints, - }); - const BasisLines = []; - let addSelectiveDynamics = false; - basis._elements.values.forEach((item, idx) => { - const coord = basis.getCoordinateValueByIndex(idx).map((x) => _print(x)); - const constraintsAsString = omitConstraints - ? "" - : basis.AtomicConstraints.getAsStringByIndex(idx, atomicConstraintsCharFromBool); - if (constraintsAsString && !omitConstraints) - addSelectiveDynamics = true; - BasisLines.push([coord.join(" "), constraintsAsString, item].join(" ")); - }); - const basisContent = BasisLines.join("\n"); - const elementsLine = basis.elementCounts.map((e) => e.value).join(" "); - const countsLine = basis.elementCounts.map((e) => parseInt(`${e.count}`, 10)).join(" "); - const coordsType = materialOrConfig.basis.units === constants_1.ATOMIC_COORD_UNITS.cartesian ? "cartesian" : "direct"; - return [ - materialOrConfig.name, - "1.0", - vectorsAsString, - elementsLine, - countsLine, - // add selective dynamics only if there are some constraints! - ...(addSelectiveDynamics ? ["Selective dynamics"] : []), - coordsType, - basisContent, - ].join("\n"); -} -/** - * @summary calculates the number of atoms in a poscar file based on the summation of the numbers in line 7 of the file. - * Poscar file formatting: https://www.vasp.at/wiki/index.php/POSCAR - */ -function atomsCount(poscarFileContent) { - const lines = utils_1.Utils.str.removeCommentsFromSourceCode(poscarFileContent).split("\n"); - const atomsLine = lines[6].split(/\s+/); - return atomsLine.map((x) => parseInt(x, 10)).reduce((a, b) => a + b); -} -/** - * Parses POSCAR file into a Material config object. - * @param fileContent - POSCAR file content. - * @return Material config. - */ -function fromPoscar(fileContent) { - const cleanContent = utils_1.Utils.str.removeCommentsFromSourceCode(fileContent, "fortran"); - const lines = cleanContent.split("\n"); - const comment = lines[0]; - // TODO: alat should be handled!!!! - // const latticeConstant = parseFloat(lines[1].trim()); - // Atom symbols and counts - const atomSymbols = lines[5].trim().split(/\s+/); - const atomCounts = lines[6].trim().split(/\s+/).map(Number); - // Check if selective dynamics and coordinates type is used - let selectiveDynamics = false; - let coordinateType = ""; - let startLine = 7; - if (lines[startLine].trim()[0].toLowerCase() === "s") { - selectiveDynamics = true; - coordinateType = lines[8].trim()[0].toLowerCase(); - startLine = 9; - } - else { - coordinateType = lines[7].trim()[0].toLowerCase(); - startLine = 8; - } - const elements = atomSymbols - .map((symbol, i) => Array(atomCounts[i]).fill(symbol)) - .reduce((a, b) => a.concat(b), []); - // Atom coordinates and constraints - const coordinates = []; - const constraints = []; - let atomIndex = 0; - for (let i = 0; i < atomSymbols.length; i++) { - for (let j = 0; j < atomCounts[i]; j++) { - const lineComponents = lines[startLine + atomIndex].trim().split(/\s+/); - const coordinate = [ - parseFloat(lineComponents[0]), - parseFloat(lineComponents[1]), - parseFloat(lineComponents[2]), - ]; - coordinates.push(coordinate); - // Add constraints if selective dynamics is used - if (selectiveDynamics) { - const constraint = [ - lineComponents[3] === "T", - lineComponents[4] === "T", - lineComponents[5] === "T", - ]; - constraints.push(constraint); - } - atomIndex += 1; - } - } - const lattice = lattice_1.Lattice.fromVectorsArray([ - lines[2].trim().split(/\s+/).map(Number), - lines[3].trim().split(/\s+/).map(Number), - lines[4].trim().split(/\s+/).map(Number), - ]); - const basis = constrained_basis_1.ConstrainedBasis.fromElementsCoordinatesAndConstraints({ - elements, - coordinates, - units: coordinateType === "c" - ? constants_1.ATOMIC_COORD_UNITS.cartesian - : constants_1.ATOMIC_COORD_UNITS.crystal, - cell: cell_1.Cell.fromVectorsArray(lattice.vectorArrays), - constraints, - }); - const materialConfig = { - lattice: lattice.toJSON(), - basis: basis.toJSON(), - name: comment, - isNonPeriodic: false, - }; - return materialConfig; -} -/** - * @summary Checks if a string has a POSCAR format (first 8 lines are read) - * @param text - string to check - */ -function isPoscar(text) { - const lines = utils_1.Utils.str.removeCommentsFromSourceCode(text, "fortran").split("\n"); - // Checking number of lines, minimum requirement for POSCAR - if (lines.length < 7) { - return false; - } - // Check the lattice constant (a single floating point number) - if (!/^[+-]?[\d.]+$/.test(lines[1].trim())) { - return false; - } - // Check the lattice vectors (three lines, each with three floating point numbers) - for (let i = 2; i <= 4; i++) { - if (!/^[-+]?\d*\.\d+\s+[-+]?\d*\.\d+\s+[-+]?\d*\.\d+$/.test(lines[i].trim())) { - return false; - } - } - // Check the atomic species line (alphabetic characters, space-separated) - if (!/^[a-zA-Z\s]+$/.test(lines[5].trim())) { - return false; - } - // Check the number of atoms per species line (digits, space-separated) - if (!/^[\d\s]+$/.test(lines[6].trim())) { - return false; - } - // Check the coordinate type line (only first character is neccessary, "s" or "S" for "Selective dynamics", - // "d" or "D" for "Direct", or "c" or "C" for "Cartesian") - if (!/^[sdc]/.test(lines[7].trim().toLowerCase())) { - return false; - } - return true; -} -exports.default = { - isPoscar, - toPoscar, - fromPoscar, - atomicConstraintsCharFromBool, - atomsCount, -}; diff --git a/dist/js/parsers/xyz.d.ts b/dist/js/parsers/xyz.d.ts deleted file mode 100644 index 560629c0e..000000000 --- a/dist/js/parsers/xyz.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { MaterialEnhancedSchema, MaterialSchema } from "@mat3ra/esse/dist/js/types"; -import { ConstrainedBasis, ConstrainedBasisConfig } from "../basis/constrained_basis"; -import { AtomicCoordinateValue } from "../basis/coordinates"; -import { AtomicElementValue } from "../basis/elements"; -import { Cell } from "../cell/cell"; -import { AtomicConstraintValue } from "../constraints/constraints"; -import { CombinatorialBasis } from "./xyz_combinatorial_basis"; -export declare const XYZ_COORDINATE_PRECISION = 4; -/** - * Validates that passed string is well-formed XYZ file. - */ -export declare function validate(xyzTxt: string): void; -export interface ParsedObject { - element: AtomicElementValue; - coordinate: AtomicCoordinateValue; - constraints: AtomicConstraintValue; - label?: number; -} -/** - * Parse XYZ text for basis. - * @param txt Text - * @param units Coordinate units - * @param cell Basis Cell - */ -declare function toBasisConfig(txt: string, units?: string, cell?: Cell): ConstrainedBasisConfig; -/** - * Create XYZ from Basis class instance. - * @param basisClsInstance Basis class instance. - * @param coordinatePrintFormat Output format for coordinates. - * @return Basis string in XYZ format - */ -declare function fromBasis(basisClsInstance: ConstrainedBasis, coordinatePrintFormat: string): string; -/** - * Create XYZ from Material class instance (or its JSON config). - * Prefer fromBasis when you already have a ConstrainedBasis instance. - */ -declare function fromMaterial(materialOrConfig: MaterialSchema | MaterialEnhancedSchema, fractional?: boolean): string; -declare const _default: { - validate: typeof validate; - fromMaterial: typeof fromMaterial; - toBasisConfig: typeof toBasisConfig; - fromBasis: typeof fromBasis; - CombinatorialBasis: typeof CombinatorialBasis; -}; -export default _default; diff --git a/dist/js/parsers/xyz.js b/dist/js/parsers/xyz.js deleted file mode 100644 index ce1477e0c..000000000 --- a/dist/js/parsers/xyz.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.XYZ_COORDINATE_PRECISION = void 0; -exports.validate = validate; -const lodash_1 = require("lodash"); -const underscore_string_1 = __importDefault(require("underscore.string")); -const constrained_basis_1 = require("../basis/constrained_basis"); -const cell_1 = require("../cell/cell"); -const lattice_1 = require("../lattice/lattice"); -const errors_1 = require("./errors"); -const xyz_combinatorial_basis_1 = require("./xyz_combinatorial_basis"); -// Regular expression for an XYZ line with atomic constraints, eg. Si 0.000000 0.500000 0.446678 1 1 1` -// eslint-disable-next-line max-len -const XYZ_LINE_REGEX = /[A-Z][a-z]?(\d)?\s+((-?\d+\.?\d*|\.\d+)\s+(-?\d+\.?\d*|\.\d+)\s+(-?\d+\.?\d*|\.\d+)(\s+)?(\s+[0-1]\s+[0-1]\s+[0-1](\s+)?)?)$/; -exports.XYZ_COORDINATE_PRECISION = 4; -/** - * Validates XYZ file's line. Line should be in following format "Si 0.5 0.5 0.5". - * Raises an error if line is in wrong format. - */ -function validateLine(xyzLine, index) { - const words = xyzLine.split(" ").filter((x) => x.trim() !== ""); - if (!xyzLine.match(XYZ_LINE_REGEX)) { - throw new errors_1.InvalidLineError(index, xyzLine); - } - const coordinates = [parseFloat(words[1]), parseFloat(words[2]), parseFloat(words[3])]; - coordinates.forEach((num, i) => { - if ((0, lodash_1.isNaN)(num)) { - throw new Error(`Coordinates should be a number. Possible error in ${i} coordinate`); - } - }); -} -/** - * Validates that passed string is well-formed XYZ file. - */ -function validate(xyzTxt) { - // The @types/underscore.string package does not provide interfaces for function chaining at the moment. Disable TS here - // @ts-ignore - (0, underscore_string_1.default)(xyzTxt) - .trim() - .lines() - .filter((x) => x.trim() !== "") - .forEach(validateLine); -} -/** - * Parses XYZ line and returns an object. - * @param line - line of text - */ -function _parseXYZLineAsWords(line) { - const words = underscore_string_1.default.words(line); - const elementWithOptionalLabel = words[0]; - const element = elementWithOptionalLabel.replace(/\d$/, ""); // Fe1 => Fe - const generateConstraintValue = (n) => parseInt(`${n}`, 10) !== 0; - const basisLineConfig = { - element, - coordinate: [+words[1], +words[2], +words[3]], - // Below maps zero values to false (atom is fixed) and non-zero values to true (atom is moving) - constraints: [ - generateConstraintValue(+words[4]), - generateConstraintValue(+words[5]), - generateConstraintValue(+words[6]), - ], - }; - if (elementWithOptionalLabel !== element) { - return { - ...basisLineConfig, - label: parseInt(elementWithOptionalLabel[elementWithOptionalLabel.length - 1], 10), - }; - } - return basisLineConfig; -} -/** - * Parse XYZ text for basis. - * @param txt Text - * @param units Coordinate units - * @param cell Basis Cell - */ -function toBasisConfig(txt, units = "angstrom", cell = new cell_1.Cell()) { - // @ts-ignore - const lines = (0, underscore_string_1.default)(txt).trim().lines(); - const listOfObjects = (0, lodash_1.map)(lines, _parseXYZLineAsWords); - const basisConfig = { - elements: listOfObjects.map((elm, idx) => { - return { - id: idx, - value: elm.element, - }; - }), - coordinates: listOfObjects.map((elm, idx) => { - return { - id: idx, - value: elm.coordinate, - }; - }), - units, - cell, - constraints: listOfObjects.map((elm, idx) => { - return { - id: idx, - value: elm.constraints, - }; - }), - }; - const labels = []; - listOfObjects.forEach((elm, idx) => { - if (elm.label) { - labels.push({ - id: idx, - value: elm.label, - }); - } - }); - if (!(0, lodash_1.isEmpty)(labels)) { - return { - ...basisConfig, - labels, - }; - } - return basisConfig; -} -/** - * Create XYZ from Basis class instance. - * @param basisClsInstance Basis class instance. - * @param coordinatePrintFormat Output format for coordinates. - * @return Basis string in XYZ format - */ -function fromBasis(basisClsInstance, coordinatePrintFormat) { - const XYZArray = basisClsInstance.getAtomicPositionsWithConstraintsAsStrings(coordinatePrintFormat, exports.XYZ_COORDINATE_PRECISION); - return `${XYZArray.join("\n")}\n`; -} -/** - * Create XYZ from Material class instance (or its JSON config). - * Prefer fromBasis when you already have a ConstrainedBasis instance. - */ -function fromMaterial(materialOrConfig, fractional = false) { - const lattice = new lattice_1.Lattice(materialOrConfig.lattice); - const constraints = "constraints" in materialOrConfig.basis ? materialOrConfig.basis.constraints : []; - const basis = new constrained_basis_1.ConstrainedBasis({ - ...materialOrConfig.basis, - cell: cell_1.Cell.fromVectorsArray(lattice.vectorArrays), - constraints, - }); - if (fractional) { - basis.toCrystal(); - } - return fromBasis(basis, "%11.6f"); -} -exports.default = { - validate, - fromMaterial, - toBasisConfig, - fromBasis, - CombinatorialBasis: xyz_combinatorial_basis_1.CombinatorialBasis, -}; diff --git a/dist/js/parsers/xyz_combinatorial_basis.d.ts b/dist/js/parsers/xyz_combinatorial_basis.d.ts deleted file mode 100644 index b8ed5f405..000000000 --- a/dist/js/parsers/xyz_combinatorial_basis.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { BasisSchema } from "@mat3ra/esse/dist/js/types"; -import { ElementsAndCoordinatesConfig } from "../basis/basis"; -import { AtomicCoordinateValue } from "../basis/coordinates"; -import { AtomicElementValue } from "../basis/elements"; -import { Cell } from "../cell/cell"; -export type ElementWithCoordinate = { - element: AtomicElementValue; - coordinate: AtomicCoordinateValue; -}; -export declare class WrongBasisFormat extends Error { - xyz: string; - constructor(xyz: string, message: string, code: number); -} -export declare class CombinatorialBasis { - _xyz: string; - _lines: any[]; - _hasPermutationLine: boolean; - _hasCombinationLine: boolean; - constructor(eXYZ: string); - /** - * Parses combinatorial basis line and returns result as Object. Throws exception if line is not valid: - * - does not meet RegExp - * - mixes permutation and combination - * @param str {String} Combinatorial basis' line - * @param index {Number} order of the - * @return {{displayName: string, isCombination: boolean, isPermutation: boolean, elements: Array, coordinates: *[]}} - * @private - */ - _parseBasisLine(str: string, index: number): { - displayName: string; - isCombination: boolean; - isPermutation: boolean; - elements: string[]; - coordinate: number[]; - }; - /** - * Returns array of ALL unique elements used in basis. - * @return {String[]} - */ - get uniqueElements(): any[]; - static toBasisConfigForElementsAndCoordinates(array: ElementWithCoordinate[], units?: BasisSchema["units"], cell?: Cell): ElementsAndCoordinatesConfig; - /** - * Returns array of regular bases extracted from current combinatorial basis. - * @return {Basis[]|Object[]} - */ - get allBasisConfigs(): ElementsAndCoordinatesConfig[]; - /** - * Returns array of regular bases extracted from current combinatorial basis with combinations. - * @private - */ - _combination(): ElementWithCoordinate[][]; - /** - * Returns array of regular bases extracted from current combinatorial basis with permutations. - * @return {Basis[]} - * @private - */ - _permutation(): ElementWithCoordinate[][]; - /** - * Returns true if current combinatorial basis contains more than one regular basis. - * @return {Boolean} - */ - isCombinatorial(): boolean; -} diff --git a/dist/js/parsers/xyz_combinatorial_basis.js b/dist/js/parsers/xyz_combinatorial_basis.js deleted file mode 100644 index 149f09918..000000000 --- a/dist/js/parsers/xyz_combinatorial_basis.js +++ /dev/null @@ -1,248 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CombinatorialBasis = exports.WrongBasisFormat = void 0; -const utils_1 = require("@mat3ra/utils"); -const lodash_1 = require("lodash"); -const s = __importStar(require("underscore.string")); -const cell_1 = require("../cell/cell"); -/** - * @summary Combinatorial XYZ basis class and related. Create and get all information about basis and elements in it. - * Constructor accepts string in extended XYZ format. Extended XYZ format is as follows: - * - * 1. Regular XYZ - * ``` - * Si 0.0 0.0 0.0 - * Li 0.5 0.5 0.5 - * ``` - * 2. Permutation (slash-separated) - * ``` - * Si/Ge/As 0.0 0.0 0.0 - * Si/Ge 0.5 0.5 0.0 - * ``` - * 3. Combination (comma-separated) - * ``` - * Si,Ge,As 0.0 0.0 0.0 - * Si,Ge 0.5 0.5 0.0 - * ``` - * More at: https://exabyte.atlassian.net/wiki/display/PD/Combinatorial+materials+set - */ -/** - * Regular expression for basis line. - * @type {RegExp} - */ -// eslint-disable-next-line max-len -const LINE_REGEX = /^([A-Z][a-z]?\/?,?)+\s+(-?\d+\.?\d*|\.\d+)\s+(-?\d+\.?\d*|\.\d+)\s+(-?\d+\.?\d*|\.\d+)\s*$/gi; -// vacancy characters will be used to create vacancies on basis generation -const VACANCY_CHARACTER = "Vac"; -const COMBINATION_DELIMITER = ","; -const PERMUTATION_DELIMITER = "/"; -/** - * Basis validation error codes. - * @type {{MIXING_IN_SINGLE_LINE: number, MIXING_IN_MULTI_LINES: number, REGEX_NOT_PASSED: number}} - */ -const ERROR_CODES = { - MIXING_IN_SINGLE_LINE: 1, - MIXING_IN_MULTI_LINES: 2, - REGEX_NOT_PASSED: 3, -}; -class WrongBasisFormat extends Error { - constructor(xyz, message, code) { - super(message); - this.xyz = xyz; - console.log(`Wrong basis format: ${message}, code: ${code}`); - } -} -exports.WrongBasisFormat = WrongBasisFormat; -class CombinatorialBasis { - constructor(eXYZ) { - this._xyz = eXYZ; - this._lines = s - .lines(eXYZ) - .map((x) => x.trim()) - .filter((x) => x !== "") - .map(this._parseBasisLine); - this._hasPermutationLine = this._lines.reduce((mem, a) => { - return mem || a.isPermutation; - }, false); - this._hasCombinationLine = this._lines.reduce((mem, a) => { - return mem || a.isCombination; - }, false); - if (this._hasPermutationLine && this._hasCombinationLine) { - throw new WrongBasisFormat(this._xyz, "Basis contains mixed permutation and combination.", ERROR_CODES.MIXING_IN_MULTI_LINES); - } - } - /** - * Parses combinatorial basis line and returns result as Object. Throws exception if line is not valid: - * - does not meet RegExp - * - mixes permutation and combination - * @param str {String} Combinatorial basis' line - * @param index {Number} order of the - * @return {{displayName: string, isCombination: boolean, isPermutation: boolean, elements: Array, coordinates: *[]}} - * @private - */ - _parseBasisLine(str, index) { - if (!str.match(LINE_REGEX)) { - throw new WrongBasisFormat(this._xyz, `Line #${index + 1}: "${str}" contains errors. ` + - 'Allowed formats: "Si 0 0 0", "Si/Li 0.5 0.5 0.5", "Si,Ge 0.7 0.7 0.8"', ERROR_CODES.REGEX_NOT_PASSED); - } - const containsPermutation = str.indexOf(PERMUTATION_DELIMITER) > -1; - const containsCombination = str.indexOf(COMBINATION_DELIMITER) > -1; - if (containsCombination && containsPermutation) { - throw new WrongBasisFormat(this._xyz, `Line #${index} contains mixed permutation and combination.`, ERROR_CODES.MIXING_IN_SINGLE_LINE); - } - let elements = []; - const words = s - .words(str) - .map((x) => x.trim()) - .filter((x) => x != null); - if (containsCombination) { - elements = words[0].split(COMBINATION_DELIMITER).map((x) => x.trim()); - } - else if (containsPermutation) { - elements = words[0].split(PERMUTATION_DELIMITER).map((x) => x.trim()); - } - else { - elements = [words[0]]; - } - const coordinate = [parseFloat(words[1]), parseFloat(words[2]), parseFloat(words[3])]; - return { - // TODO: define as a type - displayName: `ELEMENT_${index}`, - isCombination: containsCombination, - isPermutation: containsPermutation, - elements, - coordinate, - }; - } - /** - * Returns array of ALL unique elements used in basis. - * @return {String[]} - */ - get uniqueElements() { - return (0, lodash_1.chain)(this._lines) - .map((line) => line.elements) - .flatten() - .uniq() - .value() - .sort(); - } - static toBasisConfigForElementsAndCoordinates(array, units = "crystal", cell = new cell_1.Cell()) { - return { - elements: (0, lodash_1.map)(array, "element"), - coordinates: (0, lodash_1.map)(array, "coordinate"), - units, - cell, - }; - } - /** - * Returns array of regular bases extracted from current combinatorial basis. - * @return {Basis[]|Object[]} - */ - get allBasisConfigs() { - let result = []; - if (this._hasPermutationLine) { - result = this._permutation(); - } - else if (this._hasCombinationLine) { - result = this._combination(); - } - else { - const items = []; - this._lines.forEach((line) => { - items.push({ - element: line.elements[0], - coordinate: line.coordinate, - }); - }); - result = [items]; - } - return result.map((x) => CombinatorialBasis.toBasisConfigForElementsAndCoordinates(x)); - } - /** - * Returns array of regular bases extracted from current combinatorial basis with combinations. - * @private - */ - _combination() { - const dimensions = []; - this._lines.forEach((line) => { - const itemsSet = []; - line.elements.forEach((element) => { - // omit vacancy characters - itemsSet.push({ - element, - coordinate: line.coordinate, - }); - }); - dimensions.push(itemsSet); - }); - // @ts-ignore // We're multiplying objects with math, not numbers. No type casting will help. - const basisSet = utils_1.Utils.math.cartesianProduct.apply(null, - // @ts-ignore - dimensions); - return basisSet.map((basis) => basis.filter((entry) => entry.element !== VACANCY_CHARACTER)); - } - /** - * Returns array of regular bases extracted from current combinatorial basis with permutations. - * @return {Basis[]} - * @private - */ - _permutation() { - const maxLen = Math.max(...this._lines.map((x) => x.elements.length)); - const bases = []; - for (let i = 0; i < maxLen; i++) { - const items = []; - this._lines.forEach((line) => { - const element = line.elements.length <= i ? (0, lodash_1.last)(line.elements) : line.elements[i]; - if (element !== VACANCY_CHARACTER) { - items.push({ - element, - coordinate: line.coordinate, - }); - } - }); - bases.push(items); - } - return bases; - } - /** - * Returns true if current combinatorial basis contains more than one regular basis. - * @return {Boolean} - */ - isCombinatorial() { - return this._hasCombinationLine || this._hasPermutationLine; - } -} -exports.CombinatorialBasis = CombinatorialBasis; diff --git a/dist/js/tools/basis.d.ts b/dist/js/tools/basis.d.ts deleted file mode 100644 index c6d9cc72a..000000000 --- a/dist/js/tools/basis.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Basis } from "../basis/basis"; -/** - * Returns a repeated basis of a crystal. - * @param basis {Basis} Original basis. - * @param repetitions{Number[]} Repetition vector `[x, y, z]`, in each spatial dimension. - * @return {Basis} New Basis. - */ -declare function repeat(basis: Basis, repetitions: number[]): Basis; -/** - * Returns a set of Bases for a crystal interpolated from initial to final crystal. - * Can be used to generate atomic configurations along a chemical reaction path, for example. - * @param initialBasis {Basis} Original initialBasis. - * @param finalBasis {Basis} Final initialBasis. - * @param numberOfSteps{Number} Number of intermediate steps. - * @return {Basis[]} List of all bases. - */ -declare function interpolate(initialBasis: Basis, finalBasis: Basis, numberOfSteps?: number): Basis[]; -declare const _default: { - repeat: typeof repeat; - interpolate: typeof interpolate; -}; -export default _default; diff --git a/dist/js/tools/basis.js b/dist/js/tools/basis.js deleted file mode 100644 index 3eaabfe99..000000000 --- a/dist/js/tools/basis.js +++ /dev/null @@ -1,105 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("@mat3ra/utils"); -const lodash_1 = require("lodash"); -const coordinates_1 = require("../basis/coordinates"); -const ADD = utils_1.Utils.math.add; -const MULT = utils_1.Utils.math.multiply; -/** - * Returns a repeated basis of a crystal. - * @param basis {Basis} Original basis. - * @param repetitions{Number[]} Repetition vector `[x, y, z]`, in each spatial dimension. - * @return {Basis} New Basis. - */ -function repeat(basis, repetitions) { - let i, j, k; - let shiftI = 0; - let shiftJ = 0; - let shiftK = 0; - // clone original basis and assert it is in cartesian coordinates - const newBasis = basis.clone(); - const basisCloneInCrystalCoordinates = basis.clone(); - newBasis.toCrystal(); - basisCloneInCrystalCoordinates.toCrystal(); - for (i = 1; i <= repetitions[0]; i += 1) { - for (j = 1; j <= repetitions[1]; j += 1) { - for (k = 1; k <= repetitions[2]; k += 1) { - // for each atom in original basis add one with a repetition - // eslint-disable-next-line no-loop-func - basisCloneInCrystalCoordinates.elements.forEach((element, index) => { - const coord = basisCloneInCrystalCoordinates.getCoordinateValueByIndex(index); - // only add atoms if shifts are non-zero - if (shiftI || shiftJ || shiftK) { - const coordinateInstance = coordinates_1.Coordinate.fromValueAndId(coord); - const translatedCoordinateInstance = coordinateInstance.translateByVector([ - shiftI, - shiftJ, - shiftK, - ]); - newBasis.addAtom({ - element: element.value, - coordinate: translatedCoordinateInstance.value, - }); - } - }); - shiftK += 1; - } - shiftK = 0; - shiftJ += 1; - } - shiftJ = 0; - shiftI += 1; - } - if (basis.isInCartesianUnits) - newBasis.toCartesian(); - return newBasis; -} -/** - * Calculates linear function `y = kx + b` for vectors. Isolated for modularity. - * @param initialCoordinate {Array} - b. - * @param delta {Array} - x. - * @param normalizedStepIndex {Number} - k. - * @return {Basis[]} List of all bases. - */ -function _linearInterpolation(initialCoordinate, delta, normalizedStepIndex) { - return ADD(initialCoordinate, MULT(delta, normalizedStepIndex)); -} -/** - * Returns a set of Bases for a crystal interpolated from initial to final crystal. - * Can be used to generate atomic configurations along a chemical reaction path, for example. - * @param initialBasis {Basis} Original initialBasis. - * @param finalBasis {Basis} Final initialBasis. - * @param numberOfSteps{Number} Number of intermediate steps. - * @return {Basis[]} List of all bases. - */ -function interpolate(initialBasis, finalBasis, numberOfSteps = 1) { - // check that initial and final basis have the same cell - if (!initialBasis.hasEquivalentCellTo(finalBasis)) - throw new Error("basis.interpolate: Basis cells are not equal"); - // clone original initialBasis and assert it is in cartesian coordinates - const initialBasisCopy = initialBasis.clone(); - const finalBasisCopy = finalBasis.clone(); - initialBasisCopy.toCrystal(); - finalBasisCopy.toCrystal(); - const initialCoordinates = (0, lodash_1.flatten)(initialBasisCopy.coordinatesAsArray); - const finalCoordinates = (0, lodash_1.flatten)(finalBasisCopy.coordinatesAsArray); - const delta = ADD(finalCoordinates, MULT(initialCoordinates, -1)); - const resultingListOfBases = []; - for (let i = 1; i <= numberOfSteps; i++) { - const normalizedStepIndex = i / (numberOfSteps + 1); - const intermediateCoordinates = _linearInterpolation(initialCoordinates, delta, normalizedStepIndex); - const vectorSize = 3; - const intermediateCoordinatesAsNestedArray = (0, lodash_1.chunk)(intermediateCoordinates, vectorSize); - const intermediateBasis = initialBasis.clone(); - intermediateBasis.coordinates = intermediateCoordinatesAsNestedArray.map((coordinate, index) => ({ - id: index, - value: coordinate, - })); - resultingListOfBases.push(intermediateBasis); - } - return resultingListOfBases; -} -exports.default = { - repeat, - interpolate, -}; diff --git a/dist/js/tools/cell.d.ts b/dist/js/tools/cell.d.ts deleted file mode 100644 index f0b6a4f24..000000000 --- a/dist/js/tools/cell.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Coordinate3DSchema, Matrix3X3Schema } from "@mat3ra/esse/dist/js/types"; -/** - * Returns the list of points on the original lattice contained in the supercell in fractional coordinates. - * Source: https://pymatgen.org/_modules/pymatgen/util/coord.html - */ -declare function latticePointsInSupercell(supercellMatrix: Matrix3X3Schema): Coordinate3DSchema[]; -declare const _default: { - latticePointsInSupercell: typeof latticePointsInSupercell; -}; -export default _default; diff --git a/dist/js/tools/cell.js b/dist/js/tools/cell.js deleted file mode 100644 index 612c26972..000000000 --- a/dist/js/tools/cell.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("@mat3ra/utils"); -const cell_1 = require("../cell/cell"); -/** - * Returns the list of points on the original lattice contained in the supercell in fractional coordinates. - * Source: https://pymatgen.org/_modules/pymatgen/util/coord.html - */ -function latticePointsInSupercell(supercellMatrix) { - const supercell = cell_1.Cell.fromVectorsArray(supercellMatrix); - const diagonals = [ - [0, 0, 0], - [0, 0, 1], - [0, 1, 0], - [0, 1, 1], - [1, 0, 0], - [1, 0, 1], - [1, 1, 0], - [1, 1, 1], - ]; - const d_points = diagonals.map((point) => supercell.convertPointToCartesian(point)); - const mins = [0, 1, 2].map((i) => utils_1.Utils.math.min(...d_points.map((p) => p[i]))); - const maxes = [0, 1, 2].map((i) => utils_1.Utils.math.max(...d_points.map((p) => p[i])) + 1); - const points = []; - for (let i = mins[0]; i <= maxes[0]; i++) { - for (let j = mins[1]; j <= maxes[1]; j++) { - for (let k = mins[2]; k <= maxes[2]; k++) { - points.push(supercell.convertPointToCrystal([i, j, k])); - } - } - } - return points; -} -exports.default = { - latticePointsInSupercell, -}; diff --git a/dist/js/tools/index.d.ts b/dist/js/tools/index.d.ts deleted file mode 100644 index 491de39bb..000000000 --- a/dist/js/tools/index.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -declare const _default: { - surface: { - generateConfig: (material: import("../Material").default, millerIndices: import("@mat3ra/esse/dist/js/types").Coordinate3DSchema, numberOfLayers?: number, vx?: number, vy?: number) => import("./surface").SlabConfigSchema; - }; - supercell: { - generateConfig: (material: import("../Material").default, supercellMatrix: import("@mat3ra/esse/dist/js/types").Matrix3X3Schema) => { - name: string; - basis: import("../basis/basis").BasisConfig & import("@mat3ra/esse/dist/js/types").BaseInMemoryEntitySchema; - lattice: import("@mat3ra/esse/dist/js/types").LatticeSchema; - }; - generateNewBasisWithinSupercell: (basis: import("../made").Basis | import("../basis/constrained_basis").ConstrainedBasis, cell: import("../made").Cell, supercell: import("../made").Cell, supercellMatrix: import("@mat3ra/esse/dist/js/types").Matrix3X3Schema) => import("../made").Basis; - }; - material: { - scaleOneLatticeVector: (material: import("../Material").default, key?: "a" | "b" | "c", factor?: number) => void; - scaleLatticeToMakeNonPeriodic: (material: import("../Material").default) => void; - translateAtomsToCenter: (material: import("../Material").default) => void; - }; - basis: { - repeat: (basis: import("../made").Basis, repetitions: number[]) => import("../made").Basis; - interpolate: (initialBasis: import("../made").Basis, finalBasis: import("../made").Basis, numberOfSteps?: number) => import("../made").Basis[]; - }; -}; -export default _default; diff --git a/dist/js/tools/index.js b/dist/js/tools/index.js deleted file mode 100644 index 9955d2ba0..000000000 --- a/dist/js/tools/index.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const basis_1 = __importDefault(require("./basis")); -const material_1 = __importDefault(require("./material")); -const supercell_1 = __importDefault(require("./supercell")); -const surface_1 = __importDefault(require("./surface")); -exports.default = { - surface: surface_1.default, - supercell: supercell_1.default, - material: material_1.default, - basis: basis_1.default, -}; diff --git a/dist/js/tools/material.d.ts b/dist/js/tools/material.d.ts deleted file mode 100644 index a51db38da..000000000 --- a/dist/js/tools/material.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import Material from "../Material"; -/** - * Scales one lattice vector for the given material - * @param material {Material} The material acted upon. - * @param key {String} Lattice vector key. - * @param factor {Number} Float scaling factor. - */ -declare function scaleOneLatticeVector(material: Material, key?: "a" | "b" | "c", factor?: number): void; -/** - * Updates the size of a materials lattice using the minimumLatticeSize function. - * The new size of the material is calculated based on the materials basis. - * @param material {Material} - */ -declare function scaleLatticeToMakeNonPeriodic(material: Material): void; -/** - * Updates the basis of a material by translating the coordinates - * so that the center of the material and lattice are aligned. - * @param material {Material} - * */ -declare function translateAtomsToCenter(material: Material): void; -declare const _default: { - scaleOneLatticeVector: typeof scaleOneLatticeVector; - scaleLatticeToMakeNonPeriodic: typeof scaleLatticeToMakeNonPeriodic; - translateAtomsToCenter: typeof translateAtomsToCenter; -}; -export default _default; diff --git a/dist/js/tools/material.js b/dist/js/tools/material.js deleted file mode 100644 index 956e04c9a..000000000 --- a/dist/js/tools/material.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("@mat3ra/utils"); -const constants_1 = require("../constants"); -const lattice_1 = require("../lattice/lattice"); -/** - * Scales one lattice vector for the given material - * @param material {Material} The material acted upon. - * @param key {String} Lattice vector key. - * @param factor {Number} Float scaling factor. - */ -function scaleOneLatticeVector(material, key = "a", factor = 1.0) { - const lattice = { ...material.lattice }; - if (lattice.vectors === undefined) { - throw new Error("Lattice vectors are undefined"); - } - lattice.vectors[key] = lattice.vectors[key].map((v) => v * factor); - material.setLattice(lattice_1.Lattice.fromVectors(lattice.vectors).toJSON()); -} -/** - * Updates the size of a materials lattice using the minimumLatticeSize function. - * The new size of the material is calculated based on the materials basis. - * @param material {Material} - */ -function scaleLatticeToMakeNonPeriodic(material) { - material.setLattice(lattice_1.Lattice.fromConfigPartial({ - a: material.getBasis().getMinimumLatticeSize(), - type: "CUB", - }).toJSON()); -} -/** - * Updates the basis of a material by translating the coordinates - * so that the center of the material and lattice are aligned. - * @param material {Material} - * */ -function translateAtomsToCenter(material) { - const basis = material.getBasis(); - const originalUnits = basis.units; - material.toCartesian(); - const updatedBasis = basis.toCartesian(); - const centerOfCoordinates = updatedBasis.centerOfCoordinatesPoint; - const centerOfLattice = utils_1.Utils.math.multiply(0.5, material.getLattice().vectorArrays.reduce((a, b) => utils_1.Utils.math.add(a, b))); - const translationVector = utils_1.Utils.math.subtract(centerOfLattice, centerOfCoordinates); - updatedBasis.translateByVector(translationVector); - material.setBasis(updatedBasis.toJSON()); - if (originalUnits !== constants_1.ATOMIC_COORD_UNITS.cartesian) - material.toCrystal(); -} -exports.default = { - scaleOneLatticeVector, - scaleLatticeToMakeNonPeriodic, - translateAtomsToCenter, -}; diff --git a/dist/js/tools/supercell.d.ts b/dist/js/tools/supercell.d.ts deleted file mode 100644 index 8ba38536a..000000000 --- a/dist/js/tools/supercell.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Matrix3X3Schema } from "@mat3ra/esse/dist/js/types"; -import { Basis } from "../basis/basis"; -import { ConstrainedBasis } from "../basis/constrained_basis"; -import { Cell } from "../cell/cell"; -import type { MaterialSchemaMap } from "../Material"; -import type Material from "../Material"; -/** - * @summary Generates new basis for a supercell. For each site from basis generates shifts that are within supercell. - */ -declare function generateNewBasisWithinSupercell(basis: Basis | ConstrainedBasis, cell: Cell, supercell: Cell, supercellMatrix: Matrix3X3Schema): Basis; -/** - * @summary Generates supercell config for the specified material. - */ -declare function generateConfig(material: Material, supercellMatrix: Matrix3X3Schema): { - name: string; - basis: import("../basis/basis").BasisConfig & import("@mat3ra/esse/dist/js/types").BaseInMemoryEntitySchema; - lattice: import("@mat3ra/esse/dist/js/types").LatticeSchema; -}; -declare const _default: { - generateConfig: typeof generateConfig; - generateNewBasisWithinSupercell: typeof generateNewBasisWithinSupercell; -}; -export default _default; diff --git a/dist/js/tools/supercell.js b/dist/js/tools/supercell.js deleted file mode 100644 index e9ef16801..000000000 --- a/dist/js/tools/supercell.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("@mat3ra/utils"); -const lattice_1 = require("../lattice/lattice"); -const cell_1 = __importDefault(require("./cell")); -const ADD = utils_1.Utils.math.add; -/** - * @summary Generates new basis for a supercell. For each site from basis generates shifts that are within supercell. - */ -function generateNewBasisWithinSupercell(basis, cell, supercell, supercellMatrix) { - const oldBasis = basis.clone(); - const newBasis = basis.clone(); - newBasis.removeAllAtoms(); - oldBasis.toCrystal(); - newBasis.toCrystal(); - oldBasis.elements.forEach((element) => { - const coordinate = oldBasis.getCoordinateValueById(element.id); - const cartesianCoordinate = cell.convertPointToCartesian(coordinate); - const shifts = cell_1.default.latticePointsInSupercell(supercellMatrix); - shifts.forEach((combination) => { - // "combination" is effectively a point in fractional coordinates here, hence the below - const newPoint = ADD(cartesianCoordinate, supercell.convertPointToCartesian(combination)); - if (supercell.isPointInsideCell(newPoint)) { - newBasis.addAtom({ - element: element.value, - coordinate: supercell.convertPointToCrystal(newPoint), - }); - } - }); - }); - return newBasis; -} -/** - * @summary Generates supercell config for the specified material. - */ -function generateConfig(material, supercellMatrix) { - const det = utils_1.Utils.math.det(supercellMatrix); - if (det === 0) { - throw new Error("Scaling matrix is degenerate."); - } - const cell = material.getLattice().vectors; - const supercell = cell.cloneAndScaleByMatrix(supercellMatrix); - const newBasis = generateNewBasisWithinSupercell(material.getBasis(), cell, supercell, supercellMatrix); - const newLattice = lattice_1.Lattice.fromVectors({ - a: supercell.a, - b: supercell.b, - c: supercell.c, - }); - return { - name: `${material.name} - supercell ${JSON.stringify(supercellMatrix)}`, - basis: newBasis.toJSON(), - lattice: newLattice.toJSON(), - }; -} -exports.default = { - generateConfig, - generateNewBasisWithinSupercell, -}; diff --git a/dist/js/tools/surface.d.ts b/dist/js/tools/surface.d.ts deleted file mode 100644 index c5754daca..000000000 --- a/dist/js/tools/surface.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Coordinate3DSchema } from "@mat3ra/esse/dist/js/types"; -import Material, { type MaterialConfig, type MaterialSchemaMap } from "../Material"; -export type SlabConfigSchema = MaterialConfig & { - outOfPlaneAxisIndex: number; -}; -declare function generateConfig(material: Material, millerIndices: Coordinate3DSchema, numberOfLayers?: number, vx?: number, vy?: number): SlabConfigSchema; -declare const _default: { - generateConfig: typeof generateConfig; -}; -export default _default; diff --git a/dist/js/tools/surface.js b/dist/js/tools/surface.js deleted file mode 100644 index beb55ca57..000000000 --- a/dist/js/tools/surface.js +++ /dev/null @@ -1,159 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("@mat3ra/utils"); -const lattice_1 = require("../lattice/lattice"); -const supercell_1 = __importDefault(require("./supercell")); -const MULT = utils_1.Utils.math.multiply; -const ADD = utils_1.Utils.math.add; -const DOT = utils_1.Utils.math.product; -const getMatrixInLeftHandedRepresentation = (matrix) => { - return utils_1.Utils.math.det(matrix) < 0 ? MULT(matrix, -1) : matrix; -}; -/** - * Helper function for extended GCD. - * Inspired by https://gitlab.com/ase/ase/-/blob/20401e2596821a85f17ced1cb18f32c508e35fb0/ase/build/general_surface.py - * @param {Number} a - * @param {Number} b - * @return {Array} - */ -function extGCD(a, b) { - if (b === 0) - return [1, 0]; - if (utils_1.Utils.math.mod(a, b) === 0) - return [0, 1]; - const [x, y] = extGCD(b, utils_1.Utils.math.mod(a, b)); - return [y, x - y * utils_1.Utils.math.floor(a / b)]; -} -/** - * Generates a slab scaling matrix for the specified cell based on miller indices. - * Inspired by from https://gitlab.com/ase/ase/blob/master/ase/build/general_surface.py. - */ -function getMillerScalingMatrix(cell, millerIndices, tol = 1e-8) { - if (!millerIndices.reduce((a, b) => utils_1.Utils.math.abs(a) + utils_1.Utils.math.abs(b))) - throw new Error("Miller indices are zeros."); - let scalingMatrix; - const [h, k, l] = millerIndices; - const [h0, k0, l0] = millerIndices.map((i) => i === 0); - if ((h0 && k0) || (h0 && l0) || (k0 && l0)) { - // if any two indices are zero - if (!h0) { - scalingMatrix = [ - [0, 1, 0], - [0, 0, 1], - [1, 0, 0], - ]; - } - if (!k0) { - scalingMatrix = [ - [0, 0, 1], - [1, 0, 0], - [0, 1, 0], - ]; - } - if (!l0) { - scalingMatrix = [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1], - ]; - } - } - else { - const [a1, a2, a3] = cell.vectorArrays; - // z1 = (k * a1 - h * a2) - // z2 = (l * a1 - h * a3) - // z3 = l * a2 - k * a3) - const z1 = ADD(MULT(k, a1), -MULT(h, a2)); - const z2 = ADD(MULT(l, a1), -MULT(h, a3)); - const z3 = ADD(MULT(l, a2), -MULT(k, a3)); - let [p, q] = extGCD(k, l); - // @ts-ignore - const k1 = DOT(ADD(MULT(p, z1), MULT(q, z2)), z3); - // @ts-ignore - const k2 = DOT(ADD(MULT(l, z1), -MULT(k, z2)), z3); - // @ts-ignore - if (utils_1.Utils.math.abs(k2) > tol) { - // For mathjs version 3.20: round(-0.5) = -0 - // For mathjs version 5.10: round(-0.5) = -1 - // Here we specify rounding method to Bankers - // For Python 3.11: round(-0.5) = 0 - // @ts-ignore - mathjs v12 dot return type - const value = k1 / k2; - const roundedValue = utils_1.Utils.math.roundCustom(value, 0, utils_1.Utils.math.RoundingMethod.Bankers); - const i = -roundedValue; - [p, q] = [p + i * l, q - i * k]; - } - const [a, b] = extGCD(p * k + q * l, h); - const c1 = [p * k + q * l, -p * h, -q * h]; - const c2 = [0, l, -k].map((c) => utils_1.Utils.math.trunc(c / utils_1.Utils.math.gcd(l, k))); // floor division - const c3 = [b, a * p, a * q]; - scalingMatrix = [c1, c2, c3]; - } - // @ts-ignore - return getMatrixInLeftHandedRepresentation(scalingMatrix); -} -/** - * Scale the surface cell in out-of-plane direction according to thickness - * and construct the lateral supercell from vx/vy parameters. - * @param bulkCell {Cell} - * @param surfaceCell {Cell} - * @param outOfPlaneAxisIndex {Number} Index of the cell vector most collinear with the out-of-surface-plane vector - * @param thickness {Number} Surface (Slab) thickness in layers (Positive Integer). - * @param vx {Number} Size of lateral supercell along the direction of the first (x) cell vector (Positive Integer). - * @param vy {Number} Size of lateral supercell along the direction of the second (y) cell vector (Positive Integer). - */ -function getDimensionsScalingMatrix(outOfPlaneAxisIndex, thickness, vx, vy) { - const transformationMatrix = [ - [1, 0, 0], - [0, 1, 0], - [0, 0, 1], - ]; - const vxIndex = outOfPlaneAxisIndex === 2 ? 0 : outOfPlaneAxisIndex + 1; - const vyIndex = vxIndex === 2 ? 0 : vxIndex + 1; - transformationMatrix[outOfPlaneAxisIndex] = MULT(thickness, transformationMatrix[outOfPlaneAxisIndex]); - transformationMatrix[vxIndex] = MULT(vx, transformationMatrix[vxIndex]); - transformationMatrix[vyIndex] = MULT(vy, transformationMatrix[vyIndex]); - return transformationMatrix; -} -/* - * Generate a config object for a surface based on a set of parameters. - * @param material {Material} The parent material (bulk) this surface is constructed from - * @param millerIndices {Number[]} Miller Indices that define the surface cleavage. - * @param numberOfLayers {Number} Surface (Slab) thickness in layers (Positive Integer). - * @param vx {Number} Size of lateral supercell along the direction of the first (x) cell vector (Positive Integer). - * @param vy {Number} Size of lateral supercell along the direction of the second (y) cell vector (Positive Integer). - * @return {Object} - */ -function generateConfig(material, millerIndices, numberOfLayers = 1, vx = 1, vy = 1) { - if (numberOfLayers < 1) - throw new Error("Made.tools.surface.generateConfig: number of layers < 1."); - const cell = material.getLattice().vectors; - const millerScalingMatrix = getMillerScalingMatrix(cell, millerIndices); - const millerSupercell = cell.cloneAndScaleByMatrix(millerScalingMatrix); - const millerPlanePseudoNormal = cell.convertPointToCartesian(millerIndices); - const outOfPlaneAxisIndex = millerSupercell.getMostCollinearVectorIndex(millerPlanePseudoNormal); - const dimensionsScalingMatrix = getDimensionsScalingMatrix(outOfPlaneAxisIndex, numberOfLayers, vx, vy); - const supercellMatrix = MULT(dimensionsScalingMatrix, millerScalingMatrix); - const supercell = millerSupercell.cloneAndScaleByMatrix(dimensionsScalingMatrix); - const tempBasis = material.getBasis().clone(); - const newBasis = supercell_1.default.generateNewBasisWithinSupercell(tempBasis, cell, supercell, supercellMatrix); - const newLattice = lattice_1.Lattice.fromVectors({ - a: supercell.vectorArrays[0], - b: supercell.vectorArrays[1], - c: supercell.vectorArrays[2], - }); - return { - name: `${material.name} - slab ${JSON.stringify(millerIndices)}`, - basis: newBasis.toJSON(), - lattice: newLattice.toJSON(), - // extra parameter for use in creating vacuum etc. - outOfPlaneAxisIndex, - metadata: {}, - }; -} -exports.default = { - generateConfig, -}; diff --git a/package-lock.json b/package-lock.json index 8f85132ad..299c9dad4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -31,11 +31,11 @@ "@babel/register": "^7.29.7", "@babel/runtime-corejs3": "^7.29.7", "@exabyte-io/eslint-config": "^2026.7.3-0", - "@mat3ra/code": "2026.8.13-0", - "@mat3ra/esse": "2026.8.13-0", + "@mat3ra/code": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", + "@mat3ra/esse": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", "@mat3ra/standata": "2026.6.30-0", "@mat3ra/tsconfig": "^2024.6.3-0", - "@mat3ra/utils": "^2026.7.8-0", + "@mat3ra/utils": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", "@types/crypto-js": "^4.2.2", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", @@ -3019,9 +3019,9 @@ "license": "MIT" }, "node_modules/@mat3ra/code": { - "version": "2026.8.13-0", - "resolved": "https://registry.npmjs.org/@mat3ra/code/-/code-2026.8.13-0.tgz", - "integrity": "sha512-O1FY3b7RvA/ke2AXu64FrKquVxGDFYbQswTiFSdS2LXDuY6Y70sZf3j6GboIQkEMtDiy5v52kDNHeLOKwo7fAw==", + "version": "0.0.0", + "resolved": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", + "integrity": "sha512-N9VT/Kf1tU0UHZVkxiBc90++CG3vnS4JQIghkyAqYUv9V7c/OSCScPSPGqujkz+X767QuEQHQBFlU6ANe3aMVQ==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -3118,9 +3118,9 @@ } }, "node_modules/@mat3ra/esse": { - "version": "2026.8.13-0", - "resolved": "https://registry.npmjs.org/@mat3ra/esse/-/esse-2026.8.13-0.tgz", - "integrity": "sha512-3kMngHQV0l0V/XOYNcJab1I/Vyr7u2gIbxsUuhRmxR+7sIRpx+8xc8TbqDs1u2YvzUgaRqO6zKw0yKrpcG/PXw==", + "version": "0.0.0", + "resolved": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", + "integrity": "sha512-wA2FlYqIgsYYvtNQZYSSHWzvpFXjSekFsgw641KtyI0cXuAtEpFEWWap0z9avcEA98MfexvmHfm6idTa4VBEbg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -3654,9 +3654,9 @@ } }, "node_modules/@mat3ra/utils": { - "version": "2026.7.8-0", - "resolved": "https://registry.npmjs.org/@mat3ra/utils/-/utils-2026.7.8-0.tgz", - "integrity": "sha512-l7mtptWXfiZnnG4ZdM4vCrp2XBSompra1xmaiZJBpjhOnyVpQy4D+PYordncB2lUVhGqMlD2rmK5Y29oyKQR9Q==", + "version": "0.0.0", + "resolved": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", + "integrity": "sha512-vzShVrwuC16hi2HQiZsf7sGwnbu6+azHHsshd3OUVKnup+5vlZuIiFdUTXyK1jU5hoxiecCo2Wqb22UV8vlrzQ==", "dev": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index 5206f0702..fd74a6408 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,9 @@ "url": "https://github.com/mat3ra/made.git" }, "main": "dist/js/made.js", + "files": [ + "dist" + ], "author": "Exabyte Inc.", "bugs": { "url": "https://github.com/mat3ra/made/issues" @@ -34,11 +37,11 @@ "@babel/register": "^7.29.7", "@babel/runtime-corejs3": "^7.29.7", "@exabyte-io/eslint-config": "^2026.7.3-0", - "@mat3ra/code": "2026.8.13-0", - "@mat3ra/esse": "2026.8.13-0", + "@mat3ra/code": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", + "@mat3ra/esse": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", "@mat3ra/standata": "2026.6.30-0", "@mat3ra/tsconfig": "^2024.6.3-0", - "@mat3ra/utils": "^2026.7.8-0", + "@mat3ra/utils": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", "@types/crypto-js": "^4.2.2", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", From be6ec7777c33629a9e82c14a3e77e63a2dce00dc Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Tue, 18 Aug 2026 00:29:01 +0300 Subject: [PATCH 2/6] refactor: call release-wip/cleanup-wip-releases as reusable workflows mat3ra/actions is being made public, so callers no longer need to checkout it and invoke the composite action locally; call the workflow_call reusable workflow directly instead. [release] --- .github/workflows/cleanup-wip-releases.yml | 26 +++++-------------- .github/workflows/release-wip.yml | 29 +++++----------------- 2 files changed, 12 insertions(+), 43 deletions(-) diff --git a/.github/workflows/cleanup-wip-releases.yml b/.github/workflows/cleanup-wip-releases.yml index 9a69c39b9..4fb8e9342 100644 --- a/.github/workflows/cleanup-wip-releases.yml +++ b/.github/workflows/cleanup-wip-releases.yml @@ -14,23 +14,9 @@ on: jobs: cleanup-wip-releases: - runs-on: ubuntu-latest - steps: - - name: Checkout this repository - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - - - name: Checkout actions repository - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - repository: mat3ra/actions - # TODO: drop `ref` once mat3ra/actions' js/cleanup-wip-releases merges to main - ref: chore/SOF-7942-1 - token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions - - - name: Clean up stale WIP releases - uses: ./actions/js/cleanup-wip-releases - with: - # Scheduled runs always delete; workflow_dispatch defaults to dry-run. - dry-run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry-run || 'false' }} - github-token: ${{ secrets.BOT_GITHUB_TOKEN }} + uses: mat3ra/actions/.github/workflows/cleanup-wip-releases.yml@main + with: + # Scheduled runs always delete; workflow_dispatch defaults to dry-run. + dry-run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry-run || false }} + secrets: + github-token: ${{ secrets.BOT_GITHUB_TOKEN }} diff --git a/.github/workflows/release-wip.yml b/.github/workflows/release-wip.yml index 7da3a0806..ee68f6bc7 100644 --- a/.github/workflows/release-wip.yml +++ b/.github/workflows/release-wip.yml @@ -6,26 +6,9 @@ on: push jobs: release-wip: - if: contains(github.event.head_commit.message, '[release]') - runs-on: ubuntu-latest - steps: - - name: Checkout this repository - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - lfs: true - - - name: Checkout actions repository - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - with: - repository: mat3ra/actions - # TODO: drop `ref` once mat3ra/actions' js/release-wip merges to main - ref: chore/SOF-7942-1 - token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions - - - name: Publish WIP release tarball - uses: ./actions/js/release-wip - with: - package-name: made - build-script: transpile - github-token: ${{ secrets.BOT_GITHUB_TOKEN }} + uses: mat3ra/actions/.github/workflows/release-wip.yml@main + with: + package-name: made + build-script: transpile + secrets: + github-token: ${{ secrets.BOT_GITHUB_TOKEN }} From 32ee70445d5a31d973618d2a8a92389e4c3ce18e Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Tue, 18 Aug 2026 01:12:08 +0300 Subject: [PATCH 3/6] chore: retrigger release-wip now that mat3ra/actions is public [release] From f6f57d6063250b41723858c3461a4598e93c83ed Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Tue, 18 Aug 2026 13:07:08 +0300 Subject: [PATCH 4/6] docs: shrink RELEASING.md to a stub, link to mat3ra/actions README Full explanation (why this exists, tag scheme, EINTEGRITY gotcha, cleanup policy) now lives in one place instead of duplicated near- identically across 22 repos. --- RELEASING.md | 61 ++++++++++------------------------------------------ 1 file changed, 11 insertions(+), 50 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index f94bea6e0..40593e710 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,69 +1,30 @@ # Releasing WIP builds for consumers -`dist/` is build output and is gitignored — it is not committed on any branch. Published -releases (`npm publish`, tagged versions) are unaffected: `npm pack`/`npm publish` build -their file list from the `files` field in `package.json`, not from what's tracked in git. +`dist/` is build output and is gitignored — it is not committed on any branch. CI +publishes a pre-release tarball (`wip-`) whenever a pushed commit +message contains `[release]`, via the reusable workflow at +[`mat3ra/actions`](https://github.com/mat3ra/actions#release-wip-usage-reusable-workflow). +See that README for the full explanation: why this exists, the tag/URL scheme, the +`EINTEGRITY`/npm-cache gotcha on a same-commit rebuild, and the cleanup policy. -To let a consumer (e.g. `web-app`) install a not-yet-mergeable WIP commit without -`github:mat3ra/made#branch` (which has no way to build `dist/` on install), CI publishes -a pre-release tarball asset instead. - -Releases are tagged per **commit**, not per branch: `wip-`. Each commit -gets its own immutable tag/asset URL, so a consumer pinned to a specific commit's tarball -never has the content underneath that URL silently change. - -## Publishing (CI only) - -Include `[release]` anywhere in a commit message and push. `.github/workflows/release-wip.yml` -runs the `js/release-wip` action (from [`mat3ra/actions`](https://github.com/mat3ra/actions)) -on that push, which builds, packs, and publishes the pre-release tarball asset for that -commit. Commits without the marker don't trigger it, so routine pushes stay quiet. - -There is no local/manual equivalent — building and publishing only happens in CI, so the -tarball a consumer installs is always reproducible from a pushed commit, not from -whatever happens to be on someone's machine. - -The download URL follows this shape: +Download URL shape: ```text https://github.com/mat3ra/made/releases/download/wip-/made.tgz ``` -Re-triggering CI **on the same commit** (e.g. re-running the workflow) re-uploads over -that commit's existing asset (`gh release upload ... --clobber`) rather than minting a -duplicate. A new commit always gets a new tag/URL. - -## Reinstalling in a consumer after a same-commit rebuild - -Because a same-commit rebuild re-uploads over that commit's existing tag/asset, the -download URL doesn't change — which means a plain `npm install` in the consumer won't -pick up the rebuild: npm's cache stores the tarball keyed by URL, and -`package-lock.json` pins the `integrity` hash from the first install, so a -same-URL-but-changed-content refetch either gets served stale from cache or fails with -`EINTEGRITY`. Force a real refetch instead. In `web-app`, use the wrapper script from -repo root: +Reinstall in `web-app` after a same-commit rebuild (plain `npm install` won't refetch — +see the linked README for why): ```bash npm run mat3ra:install -- made wip- ``` -(`web-app/scripts/mat3ra-install.sh` — installs `@mat3ra/made@` with -`--legacy-peer-deps --force`.) - Delete a pre-release once its commit merges and a real published version supersedes it: ```bash gh release delete wip- --yes ``` -(Or let `cleanup-wip-releases.yml`, below, do it automatically once that commit is no -longer any branch's tip.) - -## Automatic cleanup - -`.github/workflows/cleanup-wip-releases.yml` runs weekly (Monday 06:00 UTC) via the -`js/cleanup-wip-releases` action and deletes any `wip-*` release whose commit is no -longer the tip of any branch. This is branch-aware, not age-based, and never deletes -anything not marked pre-release, regardless of tag. Trigger it manually from the Actions -tab (`workflow_dispatch`, defaults to `dry-run: true`) to test or force an off-schedule -cleanup. +(Or let this repo's `cleanup-wip-releases.yml` do it automatically once that commit is +no longer any branch's tip.) From b1c78df802f69b18cd62fa3d80b6163d009374b3 Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Tue, 18 Aug 2026 14:49:39 +0300 Subject: [PATCH 5/6] fix: run full build before npm publish via prepublishOnly The js/publish action never ran a build step - it relied entirely on dist/ already being committed to git. Since dist/ was gitignored in this rollout, a real `npm publish` on merge would ship whatever partial/stale dist/ happens to exist in the CI workspace instead of a full build (already caused broken @mat3ra/esse@2026.8.18-0 and @mat3ra/utils@2026.8.18-0 releases). Adding prepublishOnly (an npm lifecycle hook npm publish runs automatically) running the same build script already used and verified by release-wip.yml. Verified locally: rm -rf dist && npm run prepublishOnly produces a complete dist/. --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index fd74a6408..9616c9706 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "prettier": "prettier --check src/js tests/js", "test": "nyc --reporter=text mocha --recursive --bail tests/js/**/*.ts", "generate-mixins": "ts-node scripts/generate-mixins.ts", - "transpile": "tsc -p tsconfig-transpile.json" + "transpile": "tsc -p tsconfig-transpile.json", + "prepublishOnly": "npm run transpile" }, "repository": { "type": "git", From 298b67c5539f2a88f8bb55de4d688e27b9b585dc Mon Sep 17 00:00:00 2001 From: Kostiantyn Dvornik Date: Wed, 19 Aug 2026 00:59:52 +0300 Subject: [PATCH 6/6] chore: point @mat3ra/esse, @mat3ra/code, @mat3ra/utils at published versions All three merged and published clean (esse 2026.8.18-2, code 2026.8.18-0, utils 2026.8.18-1), superseding the WIP tarball URLs. made's own test suite doesn't need a pre-built dist/ (verified via rm -rf dist && npm test - 102/102 pass), so no pretest hook needed here unlike standata#149. [release] --- package-lock.json | 24 ++++++++++++------------ package.json | 6 +++--- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/package-lock.json b/package-lock.json index 299c9dad4..47342e727 100644 --- a/package-lock.json +++ b/package-lock.json @@ -31,11 +31,11 @@ "@babel/register": "^7.29.7", "@babel/runtime-corejs3": "^7.29.7", "@exabyte-io/eslint-config": "^2026.7.3-0", - "@mat3ra/code": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", - "@mat3ra/esse": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", + "@mat3ra/code": "2026.8.18-0", + "@mat3ra/esse": "2026.8.18-2", "@mat3ra/standata": "2026.6.30-0", "@mat3ra/tsconfig": "^2024.6.3-0", - "@mat3ra/utils": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", + "@mat3ra/utils": "2026.8.18-1", "@types/crypto-js": "^4.2.2", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", @@ -3019,9 +3019,9 @@ "license": "MIT" }, "node_modules/@mat3ra/code": { - "version": "0.0.0", - "resolved": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", - "integrity": "sha512-N9VT/Kf1tU0UHZVkxiBc90++CG3vnS4JQIghkyAqYUv9V7c/OSCScPSPGqujkz+X767QuEQHQBFlU6ANe3aMVQ==", + "version": "2026.8.18-0", + "resolved": "https://registry.npmjs.org/@mat3ra/code/-/code-2026.8.18-0.tgz", + "integrity": "sha512-/dhzWGHiH824MKoL0ZNNGD8jGyYqnWoIgoCyIJXgwMwav4Bm9hZIzumBnbpAn/mQD7MEC3l84L03uNllehMEuA==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -3118,9 +3118,9 @@ } }, "node_modules/@mat3ra/esse": { - "version": "0.0.0", - "resolved": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", - "integrity": "sha512-wA2FlYqIgsYYvtNQZYSSHWzvpFXjSekFsgw641KtyI0cXuAtEpFEWWap0z9avcEA98MfexvmHfm6idTa4VBEbg==", + "version": "2026.8.18-2", + "resolved": "https://registry.npmjs.org/@mat3ra/esse/-/esse-2026.8.18-2.tgz", + "integrity": "sha512-SMkofrqu/P5EKwTkgpi1Q5Mxfca6ZIvhWEK+YeUJDqu203+Z6plAaKx4N4xWFEt91jzNI5Slml/EFiaoVbiFzw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -3654,9 +3654,9 @@ } }, "node_modules/@mat3ra/utils": { - "version": "0.0.0", - "resolved": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", - "integrity": "sha512-vzShVrwuC16hi2HQiZsf7sGwnbu6+azHHsshd3OUVKnup+5vlZuIiFdUTXyK1jU5hoxiecCo2Wqb22UV8vlrzQ==", + "version": "2026.8.18-1", + "resolved": "https://registry.npmjs.org/@mat3ra/utils/-/utils-2026.8.18-1.tgz", + "integrity": "sha512-0J9s42sL/2S9tuwjUbxwo6/ORlGCbCvEqYSmHZgSmHNfzIc2mwuiXRNF0S5Al9EJDfYy6VO4WabDCrfpvCci8A==", "dev": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index 9616c9706..fec822db2 100644 --- a/package.json +++ b/package.json @@ -38,11 +38,11 @@ "@babel/register": "^7.29.7", "@babel/runtime-corejs3": "^7.29.7", "@exabyte-io/eslint-config": "^2026.7.3-0", - "@mat3ra/code": "https://github.com/mat3ra/code/releases/download/wip-c893e27/code.tgz", - "@mat3ra/esse": "https://github.com/mat3ra/esse/releases/download/wip-b8494e3c7/esse.tgz", + "@mat3ra/code": "2026.8.18-0", + "@mat3ra/esse": "2026.8.18-2", "@mat3ra/standata": "2026.6.30-0", "@mat3ra/tsconfig": "^2024.6.3-0", - "@mat3ra/utils": "https://github.com/mat3ra/utils/releases/download/wip-8b2c388/utils.tgz", + "@mat3ra/utils": "2026.8.18-1", "@types/crypto-js": "^4.2.2", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0",