Core Crystalline Builder

CrystalNPs.py

class pyNanoMatBuilder.crystalNPs.Crystal(crystal: str = 'Au', scaleDmin2: float = None, setSymbols2: ndarray = None, userDefCif: str = None, shape: str = 'sphere', size: float = None, directionsPPD: ndarray = None, buildPPD: str = 'xyz', directionWire: float = None, directionCylinder: float = None, refPlaneWire: float = None, nRotWire: int = 6, hollow_sphere_diameter: float = None, surfacesWulff: ndarray = None, eSurfacesWulff: ndarray = None, sizesWulff: ndarray = None, symWulff: bool = True, aseSymPrec: float = 0.0001, pbc: bool = False, threshold: float = 0.001, dbFolder: str = None, **kwargs)

Bases: pyNMBcore

A class for generating XYZ and CIF files of crystalline nanoparticles (NPs) of various shapes and sizes, based on user-defined compounds (either by name, e.g., “Fe bcc”, or from a CIF file). The supported nanoparticle shapes include:

  • Spheres

  • Ellipsoids

  • Parallelepipeds

  • Cylinders and wires with different cross-sections

  • Wulff constructions: cube, octahedron, cuboctahedron, dodecahedron, spheroids, and their truncated versions

Key Features: - Allows to choose the NP size, shape and composition. - Supports Wulff construction with customizable surface energies. - Enables the creation of wires with defined orientations and cross-sections. - Can analyze the structure in detail, including symmetry and properties. - Offers options for core/surface differentiation based on a threshold. - Generates outputs in XYZ and CIF formats for visualization and simulations. - Provides compatibility with jMol for 3D visualization.

Additional Notes: - The symmetry analysis can be skipped to speed up computations. - Periodic boundary conditions (PBC) can be enabled if needed. - Customizable precision thresholds for structural analysis.

Initialize a Crystal nanoparticle generator with specified parameters.

Parameters:
  • crystal (str) – Chemical element or compound name (default: “Au”). See pyNMBu.ciflist() for available options.

  • scaleDmin2 (float, optional) – Scale factor for unit cell minimum dimension.

  • setSymbols2 (np.ndarray, optional) – Array of chemical symbols to replace default.

  • userDefCif (str, optional) – Path to user-defined CIF file.

  • shape (str) – Nanoparticle shape. Options: ‘sphere’, ‘ellipsoid’, ‘pppd’ (parallelepiped), ‘wire’, ‘cylinder’, or ‘Wulff: <shape>’ (default: “sphere”).

  • size (list, optional) – Size specification (format depends on shape): - Sphere: [diameter] - Ellipsoid/Parallelepiped: [size_x, size_y, size_z] - Wire/Cylinder: [cross-section diameter, length]

  • directionsPPD (np.ndarray, optional) – Three direction vectors for parallelepiped.

  • buildPPD (str) – Parallelepiped coordinate system: ‘xyz’ or ‘abc’ (default: “xyz”).

  • directionWire (list, optional) – Wire growth direction (default: [0, 0, 1]).

  • directionCylinder (list, optional) – Cylinder growth direction (default: [0, 0, 1]).

  • refPlaneWire (list, optional) – Miller indices of wire reference plane.

  • nRotWire (int) – Number of rotations for wire cross-section (default: 6).

  • hollow_sphere_diameter (list, optional) – Hollow sphere diameter (Kirkendall effect).

  • surfacesWulff (np.ndarray, optional) – Miller indices for Wulff surfaces.

  • eSurfacesWulff (np.ndarray, optional) – Surface energies for Wulff construction.

  • sizesWulff (np.ndarray, optional) – Size parameters for Wulff construction.

  • symWulff (bool) – Apply symmetry to Wulff construction (default: True).

  • jmolCrystalShape (bool) – Generate JMol visualization script (default: True).

  • aseSymPrec (float) – Symmetry precision threshold (default: 1e-4).

  • pbc (bool) – Enable periodic boundary conditions (default: False).

  • threshold (float) – Plane truncation distance threshold (default: 1e-3).

  • dbFolder (str, optional) – Database folder path for CIF files.

  • postAnalyzis (bool) – Perform post-construction analysis (default: True).

  • aseView (bool) – Enable ASE visualization (default: False).

  • thresholdCoreSurface (float) – Core/surface differentiation threshold (default: 1.0).

  • skipSymmetryAnalyzis (bool) – Skip symmetry analysis (default: False).

  • noOutput (bool) – Suppress printed output (default: False).

  • calcPropOnly (bool) – Calculate properties only without structure generation (default: False).

loadExternalCif()

Load an external CIF file and extract the crystal name.

Checks if a CIF file is already loaded to avoid redundant loading. Extracts the crystal name from specific CIF tags if available.

Raises:

SystemExit – If the CIF file is not found.

bulk(noOutput)

Retrieve bulk crystal structure parameters.

Loads CIF data from either a user-defined file or the internal database.

Parameters:

noOutput (bool) – If False, prints status information.

Raises:

SystemExit – If crystal not found and no external CIF provided.

makeSuperCell(noOutput)

Create a supercell based on the nanoparticle shape and size.

Determines the appropriate supercell dimensions based on the particle shape, then constructs and centers the supercell at the origin.

Parameters:

noOutput (bool) – If False, details are printed.

makeSphere(noOutput)

Create a spherical nanoparticle by removing atoms outside the defined radius.

Computes dimensions from the provided diameter in nanometers.

Parameters:

noOutput (bool) – If False, details are printed.

makeEllipsoid(noOutput)

Create an ellipsoidal nanoparticle by removing atoms outside the defined ellipsoid.

Parameters:

noOutput (bool) – If False, details are printed.

makeWire(noOutput=False)

Create a nanowire by truncating atoms based on reference planes.

Uses rotated planes around the growth direction to define wire cross-section. Measures and stores the wire length, radius, and volume.

Parameters:

noOutput (bool) – If False, details are printed (default: False).

Returns:

The generated nanowire structure.

Return type:

ase.Atoms

makeCylinder(noOutput=False)

Create a cylindrical nanoparticle.

Aligns the specified direction to the Z-axis, removes atoms outside the cylinder, and measures the resulting dimensions.

Parameters:

noOutput (bool) – If False, details are printed (default: False).

Returns:

The generated cylindrical nanoparticle.

Return type:

ase.Atoms

Note

size = [diameter_nm, length_nm] directionCylinder = [h, k, l]

makeParallelepiped(noOutput)

Create a parallelepiped-shaped nanoparticle.

Truncates atoms based on specified directions. If using Cartesian coordinates (“xyz”), directions are used directly. Otherwise, normal vectors are calculated and lattice transformation is applied.

Parameters:

noOutput (bool) – If False, details are printed.

makeWulff(noOutput)

Creation of Wulff nanoparticles by removing atoms above Wulff planes, to create the final shape. Determines the truncation planes and truncation distances based on provided surfaces and surface energies. Calculate for .

Parameters:

noOutput (bool) – If False, details are printed.

Note

Updates self.trPlanes with normalized truncation planes and distances. Updates self.NP with the truncated structure.

makeNP(noOutput)

Generate a nanoparticle of the specified shape.

Constructs different nanoparticle types based on user-defined shape and size. Supports spheres, ellipsoids, parallelepipeds, wires, cylinders, and Wulff constructions.

Parameters:

noOutput (bool) – If False, details are printed.

Note

Updates self.NP with the generated nanoparticle structure. Updates self.nAtoms, self.cog, and self.trPlanes attributes.

predefinedParameters4WulffShapes(noOutput)

Assign pre-defined parameters for Wulff shapes.

Retrieves pre-defined properties (truncation planes, symmetry, MOI) for Wulff shapes from the internal database. Validates shape compatibility with crystal lattice.

Parameters:

noOutput (bool) – If False, details are printed.

Note

Updates self.eSurfacesWulff, self.surfacesWulff, and self.symWulff.

prop()

Display unit cell and nanoparticle properties.

Parameters:

noOutput (bool) – If False, details are printed.

Geometric Nanoparticle Shapes

platonicNPs.py

class pyNanoMatBuilder.platonicNPs.PlatonicNP(**kwargs)

Bases: pyNMBcore

Base class for all Platonic nanoparticles providing common functionality.

Parameters:
  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

class pyNanoMatBuilder.platonicNPs.regfccOh(element: str = 'Au', Rnn: float = 2.7, nOrder: int = 1, shape: str = 'regfccOh', **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of regular fcc octahedral nanoparticles (NPs).

Generates NPs of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features:
  • Allows to choose the NP size.

  • Can analyze the structure in detail, including symmetry and properties.

  • Offers options for core/surface differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats for visualization and simulations.

  • Provides compatibility with jMol for 3D visualization.

Additional Notes:
  • The nOrder parameter determines the level of imbrication.

  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element (str) – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nOrder (int) – Determines the level of imbrication = the number of atomic layers along an edge (e.g., nOrder=1 means 2 atoms per edge).

  • shape (str) – Shape ‘regfccOh’.

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerLayer

Number of atoms in each atomic layer.

Type:

list

nAtomsPerEdge

Number of atoms per edge.

Type:

int

interLayerDistance

Distance between atomic layers.

Type:

float

jmolCrystalShape

Flag for JMol visualization.

Type:

bool

cog

Center of gravity of the NP.

Type:

np.array

imageFile

Path to a reference image.

Type:

str

trPlanes

Truncation plane equations.

Type:

array

nFaces = 8
nEdges = 12
nVertices = 6
edgeLengthF = 1
radiusCSF = np.float64(0.7071067811865476)
radiusISF = np.float64(0.40824829046386296)
radiusMSF = 0.5
dihedralAngle = np.float64(109.47122063449069)
interShellF = np.float64(1.414213562373095)
nAtomsF(i)

Returns the number of atoms of an octahedron of size i.

Parameters:

i (int) – The order or size parameter.

Returns:

The calculated number of atoms.

Return type:

int

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer (from 1 to nOrder), computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

Returns:

Total number of atoms.

Return type:

int

edgeLength()

Computes the edge length of the nanoparticle in Å.

The edge length is determined based on the interatomic distance (Rnn) and the number of atomic layers (nOrder).

Returns:

The edge length in Å.

Return type:

float

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

radiusMidSphere()

Computes the radius of the midsphere of the nanoparticle in Å.

The midsphere is a sphere that touches the edges of the nanoparticle.

Returns:

Radius.

Return type:

float

area()

Computes the surface area of the nanoparticle in square Ångströms.

Returns:

Surface area.

Return type:

float

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

Returns:

Volume.

Return type:

float

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of an octahedral nanoparticle.

Parameters:

i (int) – Index of the shell layer.

Returns:

  • CoordVertices (np.ndarray): the 6 vertex coordinates

    of the ith shell of an octahedron

  • edges (np.ndarray): indexes of the 30 edges

  • faces (np.ndarray): indexes of the 20 faces

Return type:

tuple

coords(noOutput)

Generates atomic coordinates for an octahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Adds core atoms layer by layer.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

calc_sasview_dims(noOutput)

Computes the dimensions of the nanoparticle for direct comparison with SasView models.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.platonicNPs.regIco(element: str = 'Au', Rnn: float = 2.7, nShell: int = 1, shape: str = 'regIco', double_ico: bool = False, **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of regular icosahedral nanoparticles (NPs).

Generates NPs of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features:
  • Allows to choose the NP size.

  • Can analyze the structure in detail, including symmetry and properties.

  • Offers options for core/surface differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats for visualization and simulations.

  • Provides compatibility with jMol for 3D visualization.

Additional Notes:
  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element (str) – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nShell (int) – Number of shells = the number of atomic layers along an edge (e.g., nOrder=1 means 2 atoms per edge).

  • shape (str) – Shape ‘regIco’.

  • double_ico (bool) – If True, generates a double icosahedron.

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerShell

Number of atoms in each shell.

Type:

list

interShellDistance

Distance between atomic shells.

Type:

float

jmolCrystalShape

Flag for JMol visualization.

Type:

bool

imageFile

Path to a reference image.

Type:

str

trPlanes

Truncation plane equations.

Type:

array

nFaces = 20
nEdges = 30
nVertices = 12
phi = np.float64(1.618033988749895)
edgeLengthF = 1
radiusCSF = np.float64(0.9510565162951535)
interShellF = np.float64(1.0514622242382672)
radiusISF = np.float64(0.7557613140761706)
nAtomsF(i)

Returns the number of atoms of an icosahedron of size i.

Parameters:

i (int) – The shell number or size parameter.

Returns:

The calculated number of atoms.

Return type:

int

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer, computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

Returns:

Total number of atoms.

Return type:

int

edgeLength()

Computes the edge length of the nanoparticle in Å.

The edge length is determined based on the interatomic distance (Rnn) and the number of shells (nShell).

Returns:

Edge length in Å.

Return type:

float

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

area()

Computes the surface area of the nanoparticle in square Ångströms.

Returns:

Surface area.

Return type:

float

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

Returns:

Volume.

Return type:

float

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of an icosahedral nanoparticle.

Parameters:

i (int) – Index of the shell.

Returns:

  • CoordVertices (np.ndarray): the 12 vertex coordinates of the ith shell of an icosahedron

  • edges (np.ndarray): indexes of the 30 edges

  • faces (np.ndarray): indexes of the 20 faces

Return type:

tuple

edges_to_planes(coords)

Converts a list of edges in planes equations [u, v, w, d].

Parameters:

coords (np.ndarray) – Atoms coordinates.

Returns:

List of planes equations [u, v, w, d].

Return type:

planes (list of np.ndarray)

edges_to_planes2(coords)

Converts a list of edges in planes equations [u, v, w, d].

Parameters:

coords (np.ndarray) – Atoms coordinates.

Returns:

List of planes equations [u, v, w, d].

Return type:

planes (list of np.ndarray)

coords(noOutput)

Generates atomic coordinates for an icosahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.platonicNPs.regfccTd(element: str = 'Au', Rnn: float = 2.7, nLayer: int = 1, shape: str = 'regfccTd', n_Td: int = 1, **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of regular fcc tetrahedral nanoparticles (NPs).

Generates NPs of various sizes based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features:
  • Allows to choose the NP size.

  • Can analyze the structure in detail, including symmetry and properties.

  • Offers options for core/surface differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats for visualization and simulations.

  • Provides compatibility with jMol for 3D visualization.

Additional Notes:
  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element (str) – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nLayer (int) – Number of layers, also equals to the number of atoms per edge (e.g., nOrder=2 means 2 atoms per edge).

  • shape (str) – Shape ‘regfccTd’.

  • n_Td (int) – The number of tetrahedrons in the optional helix.

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerLayer

Number of atoms in each atomic layer.

Type:

list

nAtomsPerEdge

Number of atoms per edge.

Type:

int

jmolCrystalShape

Flag for JMol visualization.

Type:

bool

cog

Center of gravity of the NP.

Type:

np.array

imageFile

Path to a reference image.

Type:

str

trPlanes

Truncation plane equations.

Type:

array

nFaces = 4
nEdges = 6
nVertices = 4
edgeLengthF = 1
heightOfPyramidF = np.float64(0.816496580927726)
radiusCSF = np.float64(0.6123724356957945)
radiusISF = np.float64(0.20412414523193154)
radiusMSF = np.float64(0.35355339059327373)
fveAngle = np.float64(54.735610317245346)
fefAngle = np.float64(70.52877936550931)
vcvAngle = np.float64(109.47122063449069)
nAtomsF(i)

Returns the number of atoms of a tetrahedron of size i.

nAtomsPerLayerAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each layer, computes the number of atoms for the given layer, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current layer.

Returns:

A list where each element represents the number of atoms

in a specific layer.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Computes the edge length of the nanoparticle in Å.

The edge length is determined based on the interatomic distance (Rnn) and the number of atomic layers (nLayer).

heightOfPyramid()

Computes the length of the height of the pyramid in Å.

interLayerDistance()

Computes the distance between the layers in Å.

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å.

radiusMidSphere()

Computes the radius of the midsphere of the nanoparticle in Å.

The midsphere is a sphere that touches the edges of the nanoparticle.

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

MakeVertices(nL)

Generates the coordinates of the vertices, edges, and faces for the ith shell of a tetrahedral nanoparticle.

Parameters:

nL (int) – number of layers = number of atoms per edge.

Returns:

the 4 vertex coordinates of a tetrahedron. - edges (np.ndarray): indexes of the 6 edges. - faces (np.ndarray): indexes of the 4 faces.

Return type:

  • CoordVertices (np.ndarray)

coords(noOutput)

Generates atomic coordinates for a tetrahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Adds core atoms layer by layer.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.platonicNPs.regDD(element: str = 'Au', Rnn: float = 2.7, nShell: int = 1, shape: str = 'regDD', **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of regular dodecahedral nanoparticles (NPs).

Generates NPs of various sizes based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features:
  • Allows to choose the NP size.

  • Can analyze the structure in detail, including symmetry and properties.

  • Offers options for core/surface differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats for visualization and simulations.

  • Provides compatibility with jMol for 3D visualization.

Additional Notes:
  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element (str) – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nShell (int) – Number of shells (e.g., nShell=1 means 2 atoms per edge).

  • shape (str) – Shape ‘regDD’.

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerShell

Number of atoms in each shell.

Type:

list

interShellDistance

Distance between shells.

Type:

float

jmolCrystalShape

Flag for JMol visualization.

Type:

bool

imageFile

Path to a reference image.

Type:

str

trPlanes

Truncation plane equations.

Type:

array

nFaces = 12
nEdges = 30
nVertices = 20
phi = np.float64(1.618033988749895)
edgeLengthF = 1
radiusCSF = np.float64(1.4012585384440734)
interShellF = np.float64(0.7136441795461799)
radiusISF = np.float64(1.1135163644116068)
nAtomsF(i)

Returns the number of atoms of a dodecahedron of size i.

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer, computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of

atoms in a specific shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Computes the edge length of the nanoparticle in Å.

The edge length is determined based on the interatomic distance (Rnn) and the number of shells (nShell).

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å.

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of a dodecahedral nanoparticle.

Parameters:

i (int) – Index of the shell.

Returns:

the 20 vertex coordinates of the ith shell of a dodecahedron. - edges (np.ndarray): indexes of the 30 edges. - faces (np.ndarray): indexes of the 12 faces.

Return type:

  • CoordVertices (np.ndarray)

coords(noOutput)

Generates atomic coordinates for a dodecahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.platonicNPs.cube(crystalStructure='fcc', element='Au', Rnn: float = 2.7, nOrder: int = 1, size: int = 0, shape: str = 'cube', **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of cubic nanoparticles (NPs).

Generates NPs of various sizes based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features:
  • Allows to choose the NP size.

  • Can analyze the structure in detail, including symmetry and properties.

  • Offers options for core/surface differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats for visualization and simulations.

  • Provides compatibility with jMol for 3D visualization.

Additional Notes:
  • The nOrder parameter determines the level of imbrication.

  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • crystalStructure (str) – The crystal structure of the NP (e.g., ‘fcc’, ‘bcc’).

  • element (str) – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nOrder (int) – Determines the level of imbrication = the number of atomic layers along an edge (e.g., nOrder=1 means 2 atoms per edge).

  • size (float) – Size of the cube in nm.

  • shape (str) – Shape of the nanoparticle. Defaults to ‘cube’.

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerShell

Number of atoms in each shell.

Type:

list

nAtomsPerEdge

Number of atoms per edge.

Type:

int

interLayerDistance

Distance between atomic layers.

Type:

float

jmolCrystalShape

Flag for JMol visualization.

Type:

bool

cog

Center of gravity of the NP.

Type:

np.array

imageFile

Path to a reference image.

Type:

str

trPlanes

Truncation plane equations.

Type:

array

nFaces = 6
nEdges = 12
nVertices = 8
edgeLengthFfcc = np.float64(1.4142135623730951)
edgeLengthFbcc = np.float64(1.1547005383792517)
radiusCSF = np.float64(0.8660254037844386)
radiusISF = 0.5
nAtomsfccF(i)

Returns the number of atoms of an fcc cube of size i x i x i.

Parameters:

i (int) – The size parameter corresponding to nOrder.

Returns:

The calculated number of atoms.

Return type:

int

nAtomsbccF(i)

Returns the number of atoms of a bcc cube of size i x i x i.

Parameters:

i (int) – The size parameter corresponding to nOrder.

Returns:

The calculated number of atoms.

Return type:

int

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer (from 1 to nOrder), computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsfccAnalytic()

Computes the total number of atoms in the fcc nanoparticle.

Returns:

Total number of atoms.

Return type:

int

nAtomsbccAnalytic()

Computes the total number of atoms in the bcc nanoparticle.

Returns:

Total number of atoms.

Return type:

int

edgeLength()

Computes the edge length of the nanoparticle in Å.

The edge length is determined based on the interatomic distance (Rnn), the number of atomic layers (nOrder) and the crystalStructure (fcc or bcc).

Returns:

The edge length in Å.

Return type:

float

latticeConstant()

Computes the lattice constant of the nanoparticle in Å.

Based on the interatomic distance (Rnn) and the crystalStructure (fcc or bcc).

Returns:

The lattice constant in Å.

Return type:

float

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å.

Returns:

Radius.

Return type:

float

area()

Computes the surface area of the nanoparticle in square Ångströms.

Returns:

Surface area.

Return type:

float

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

Returns:

Volume.

Return type:

float

coords(noOutput)

Generates atomic coordinates for a cubic nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Adds core atoms layer by layer.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.platonicNPs.hollow_shapes(full_cube, nOrder_hollow: int = 0, **kwargs)

Bases: PlatonicNP

A class for generating XYZ and CIF files of hollow cubic nanoparticles (NPs).

Creates NPs with customizable sizes and compositions. Users can define the composition by specifying element names (e.g., “Fe”, “Au”) and provide a “cube” class instance from this module to construct the nanoparticle structure.

Key Features:
  • Allows to choose the cube size and the

    size of its hollow.

  • Can analyze the structure in detail,

    including symmetry and properties.

  • Offers options for core/surface

    differentiation based on a threshold.

  • Generates outputs in XYZ and CIF formats

    for visualization and simulations.

  • Provides compatibility with jMol for 3D

    visualization.

Additional Notes:
  • The symmetry analysis can be skipped to speed up computations.

  • Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • full_cube (cube) – Instance of the class “cube” of the module “pNP”.

  • nOrder_hollow (int) – Size of the hollow in nOrder (number of atomic layers along an edge).

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nAtoms

Number of atoms in the NP.

Type:

int

cog

Center of gravity of the NP.

Type:

np.array

create_hollow(noOutput)

Function that creates the cube hollow.

The hollow is created using planes that defines the hollow [h k l d] with d= +/- size of the hollow/2. Update: the hollow size is given in nOrder of atomic layers.

Parameters:

noOutput (bool) – If False, prints details about the NP structure.

archimedeanNPs.py

class pyNanoMatBuilder.archimedeanNPs.ArchimedeanNP(**kwargs)

Bases: PlatonicNP

Base class for all Archimedean nanoparticles providing common functionality.

Parameters:
  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

class pyNanoMatBuilder.archimedeanNPs.fccCubo(element: str = 'Au', Rnn: float = 2.7, nShell: int = 1, **kwargs)

Bases: ArchimedeanNP

A class for generating XYZ and CIF files of fcc cuboctahedral nanoparticles (NPs) of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Parameters:
  • element (str) – Chemical element symbol (e.g. “Au”).

  • Rnn (float) – Nearest-neighbour distance in Å.

  • nShell (int) – Number of shells (controls imbrication).

  • postAnalyzis (bool) – If True, run post-construction analysis.

  • aseView (bool) – If True, show the structure via ASE viewer.

  • thresholdCoreSurface (float) – Threshold for core/surface separation.

  • skipSymmetryAnalyzis (bool) – If True, skip symmetry analysis.

  • jmolCrystalShape (bool) – If True, enable jMol script generation.

  • noOutput (bool) – If True, suppress printing.

  • calcPropOnly (bool) – If True, only compute properties, skip coords.

nAtoms

Number of atoms in the NP.

Type:

int

nAtomsPerShell

Number of atoms in each shell.

Type:

list

interShellDistance

Distance between shells.

Type:

float

Initialize the class with all necessary parameters.

Parameters:
  • element – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nShell (int) – Determines the level of imbrication = the number of atomic layers along an edge (e.g., nShell=1 means 2 atoms per edge).

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

self.shape

Shape ‘fccCubo’

Type:

str

self.nAtoms

Number of atoms in the NP.

Type:

int

self.nAtomsPerShell

Number of atoms in each shell.

Type:

list

self.interShellDistance

Distance between shells.

Type:

float

self.jmolCrystalShape

Flag for JMol visualization.

Type:

bool

self.imageFile

Path to a reference image.

Type:

str

self.trPlanes

Truncation plane equations.

Type:

array

nFaces = 14
nEdges = 24
nVertices = 12
edgeLengthF = 1
radiusCSF = 1
interShellF = 1.0
radiusISF = 0.75
nAtomsF(i)

Return analytic number-of-atoms factor for size i.

Parameters:

i (int) – Size/order parameter.

Returns:

Analytic count factor.

Return type:

int

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer, computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Computes the edge length of the nanoparticle in Å .

The edge length is determined based on the interatomic distance (Rnn) and the number of shells (nShell).

radiusCircumscribedSphere()

Radius of the circumscribed sphere in Å.

Returns:

Radius in Å.

Return type:

float

radiusInscribedSphere()

Radius of the inscribed sphere (Å).

Returns:

Radius in Å.

Return type:

float

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of the nanoparticle. :param - i: index of the shell :type - i: int

Returns:

  • CoordVertices = the 12 vertex coordinates of the ith shell of an icosahedron

  • edges (np.ndarray): indexes of the 30 edges

  • faces (np.ndarray): indexes of the 20 faces

coords(noOutput)

Generate the coordinates of a cuboctahedral nanoparticle.

Args: - noOutput (bool): If True, suppresses output messages.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.archimedeanNPs.fccTrTd(element: str = 'Au', Rnn: float = 2.7, nLayer: int = 1, **kwargs)

Bases: ArchimedeanNP

A class for generating XYZ and CIF files of fcc truncated tetrahedral nanoparticles (NPs) of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features: - Allows to choose the NP size. - Can analyze the structure in detail, including symmetry and properties. - Offers options for core/surface differentiation based on a threshold. - Generates outputs in XYZ and CIF formats for visualization and simulations. - Provides compatibility with jMol for 3D visualization.

Additional Notes: - The symmetry analysis can be skipped to speed up computations. - Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nLayer (int) – Number of layers, also equals to the number of atoms per edge (e.g., nLayer=2 means 2 atoms per edge).

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

self.shape

Shape ‘fccTrTd’

Type:

str

self.nAtoms

Number of atoms in the NP.

Type:

int

self.cog

Center of gravity of the NP.

Type:

np.array

self.Tdprop

Class “regfccTd” of the module “pNP” (creates regular fcc tetrahedron)

Type:

class instance

self.interLayerDistance

Distance between two layers in Å.

Type:

float

self.nAtomsPerEdge

Number of atoms per edge.

Type:

int

self.jmolCrystalShape

Flag for JMol visualization.

Type:

bool

self.imageFile

Path to a reference image.

Type:

str

self.trPlanes

Truncation plane equations.

Type:

array

nFaces3 = 4
nFaces6 = 4
nEdges = 18
nVertices = 12
edgeLengthF = 1
radiusCSF = np.float64(1.1726039399558574)
radiusMSF = np.float64(1.0606601717798214)
cutFromVertexAt = 0.3333333333333333
nAtomsF(i)

Returns a factor to compute the number of atoms of a nanoparticle of size i.

nAtomsAnalytic()

Compute the total number of atoms analytically.

Returns:

Total number of atoms for the current nAtomsPerEdge.

Return type:

int

edgeLength()

Computes the edge length of the nanoparticle in Å .

The edge length of the truncated tetrahedron equals the regular tetrahedron’s edge length divided by 3.

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

radiusMidSphere()

Radius of the midsphere (Å), tangent to edges.

Returns:

Radius in Å.

Return type:

float

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

magicEdgeNumberOfTd2MakeATrTd(index: int)

Returns the number of edge atoms of the tetrahedron that will lead to perfect trucated tetrahedron with all edges of equal atomic length.

NumberOfTdEdgeAtomsValid4ATrTd()

Calculate the number of edge atoms in a truncated tetrahedral nanoparticle and check if it is a valid integer.

Returns:

A tuple where the first element is True if the number is an integer, and the second element is the computed number of edge atoms.

Return type:

(bool, float)

coords(noOutput)

Generate coordinates for the truncated octahedron.

Parameters:

noOutput (bool) – If True, suppress printing and progress output.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.archimedeanNPs.fccTrOh(element: str = 'Au', Rnn: float = 2.7, nOrder: int = 1, **kwargs)

Bases: ArchimedeanNP

A class for generating XYZ and CIF files of fcc truncated octahedral nanoparticles (NPs) of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features: - Allows to choose the NP size. - Can analyze the structure in detail, including symmetry and properties. - Offers options for core/surface differentiation based on a threshold. - Generates outputs in XYZ and CIF formats for visualization and simulations. - Provides compatibility with jMol for 3D visualization.

Additional Notes: - The nOrder parameter determines the level of imbrication - The symmetry analysis can be skipped to speed up computations. - Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nOrder (int) – Determines the level of imbrication = the number of atomic layers along an edge (e.g., nOrder=1 means 2 atoms per edge).

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

self.Ohprop

class “regfccOh” of the module “pNP”

Type:

class instance

self.self.cog

Center of gravity of the NP.

Type:

np.array

self.nAtoms

Number of atoms in the NP.

Type:

int

self.nAtomsPerEdge

Number of atoms per edge.

Type:

int

self.interLayerDistance

Distance between atomic layers.

Type:

float

self.jmolCrystalShape

Flag for JMol visualization.

Type:

bool

self.cog

Center of gravity of the NP.

Type:

np.array

self.imageFile

Path to a reference image.

Type:

str

self.trPlanes

Truncation plane equations.

Type:

array

nFaces4 = 6
nFaces6 = 8
nEdges = 36
nVertices = 24
edgeLengthF = 1
radiusCSF = np.float64(1.5811388300841898)
radiusMSF = 1.5
radiusISF = np.float64(1.4230249470757708)
cutFromVertexAt = 0.3333333333333333
nAtomsF(i)

Factor used to compute number of atoms for size i.

Parameters:

i (int) – Size/order parameter.

Returns:

Analytic factor for atom count.

Return type:

int

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Edge length (Å) of the truncated octahedron.

Returns:

Edge length in Å.

Return type:

float

sasview_dims()

Return dimensions compatible with SasView.

In pyNanoMatBuilder truncation is defined by the ratio d(truncated_edge)/d(edge) while SasView expects the ratio d(truncated_demi_axis)/d(demi_axis). This routine computes the full demi-axis and the truncated demi-axis and returns both the demi-axis and the truncature ratio.

Returns:

(demi_axis, truncature_ratio)

Return type:

tuple

octahedron_truncated_volume(length_a, t)

Volume of a truncated octahedron with edge length length_a and truncation parameter t. t is defined as the ratio of the truncated edge length to the original edge length.

radiusCircumscribedSphere()

Computes the radius of the circumscribed sphere of the nanoparticle in Å.

radiusMidSphere()

Computes the radius of the midsphere of the nanoparticle in Å. The midsphere is a sphere that touches the edges of the nanoparticle.

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å .

area()

Surface area in Å^2.

Returns:

Surface area in square Ångström.

Return type:

float

volume()

Volume in Å^3.

Returns:

Volume in cubic Ångström.

Return type:

float

magicEdgeNumberOfOh2MakeATrOh(index: int)

Compute the number of edge atoms of the octahedron that will lead to perfect trucated tetrahedra with all edges of equal atomic length. :param index: The maximum number of edge atoms to consider. :type index: int

Returns:

An array of valid numbers of edge atoms for truncated octahedra.

Return type:

np.array

NumberOfOhEdgeAtomsValid4ATrOh()

Calculate the number of edge atoms in a truncated octahedral nanoparticle and check if it is a valid integer.

Returns:

(is_integer (bool), nTrOh (float)) where is_integer flags

whether the computed number of atoms per edge is integer.

Return type:

tuple

coords(noOutput)

Generate the coordinates of a truncated tetrahedral nanoparticle.

Args: - noOutput (bool): If True, suppresses output messages.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.archimedeanNPs.fccTrCube(element: str = 'Au', Rnn: float = 2.7, nOrder: int = 1, **kwargs)

Bases: ArchimedeanNP

Truncated cubic nanoparticle (FCC) builder.

Generates XYZ/CIF outputs for fcc truncated cubes of various sizes.

Parameters:
  • element (str) – Chemical element symbol, e.g. “Au”.

  • Rnn (float) – Nearest-neighbour distance in Å.

  • nOrder (int) – Order/size parameter (number of layers along an edge).

  • postAnalyzis (bool) – If True, run post-construction analysis.

  • aseView (bool) – If True, show the structure using ASE viewer.

  • thresholdCoreSurface (float) – Threshold for core/surface separation.

  • skipSymmetryAnalyzis (bool) – If True, skip symmetry analysis.

  • jmolCrystalShape (bool) – If True, enable jMol script generation.

  • noOutput (bool) – If True, suppress printing.

  • calcPropOnly (bool) – If True, only compute properties, skip coords.

cubeProp

Instance of pNP.cube used as base geometry.

trPlanes

Truncation plane equations (if any).

nAtomsPerEdge

Number of atoms on an edge after truncation.

Type:

int

cog

Center of gravity of the final nanoparticle.

Type:

np.ndarray

Parameters:
  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

nFaces3 = 8
nFaces8 = 6
nEdges = 36
nVertices = 24
edgeLengthF = 1
radiusCSF = np.float64(1.7788236456639244)
radiusMSF = np.float64(1.7071067811865475)
radiusISF = np.float64(1.6382813268065142)
CornersAt = np.float64(0.2928932188134524)
magic_angle = np.float64(0.9553166181245092)
cutFromVertexAt = np.float64(0.16910197872576274)
NumberOfCubeEdgeAtomsValid4ATrCube()

Calculates the approximate number of atoms remaining on an edge.

edgeLength()

Edge length in Ångström for the truncated cube.

prop()

Display unit cell and nanoparticle properties.

catalanNPs.py

class pyNanoMatBuilder.catalanNPs.CatalanNP(**kwargs)

Bases: pyNMBcore

Base class for all Catalan nanoparticles providing common functionality.

Parameters:
  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

class pyNanoMatBuilder.catalanNPs.bccrDD(element: str = 'Au', Rnn: float = 2.7, nShell: int = 1, **kwargs)

Bases: CatalanNP

A class for generating XYZ and CIF files of rhombic dodecahedral nanoparticles (NPs) of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features: - Allows to choose the NP size. - Can analyze the structure in detail, including symmetry and properties. - Offers options for core/surface differentiation based on a threshold. - Generates outputs in XYZ and CIF formats for visualization and simulations. - Provides compatibility with jMol for 3D visualization.

Additional Notes: - The symmetry analysis can be skipped to speed up computations. - Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nShell (int) – Number of shells (e.g., nShell=1 means 2 atoms per edge).

  • postAnalyzis (bool) – If True, prints additional NP information. Examples: cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation. This is the distance threshold used to decide which atoms are retained.

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

self.shape

Shape ‘bccrDD’

Type:

str

self.nAtoms

Number of atoms in the NP.

Type:

int

self.nAtomsPerShell

Number of atoms in each shell.

Type:

list

self.interShellDistance3

Distance between shells at order 3.

Type:

float

self.interShellDistance4

Distance between shells at order 4.

Type:

float

self.cog

Center of gravity of the NP.

Type:

np.array

self.jmolCrystalShape

Flag for JMol visualization.

Type:

bool

self.imageFile

Path to a reference image.

Type:

str

nFaces = 12
nEdges = 24
nVertices = 14
edgeLengthF = 1
radiusCSF3rdOrderV = 1
radiusCSF4thOrderV = np.float64(1.1547005383792515)
radiusISF = np.float64(0.8164965809277259)
radiusMSF = np.float64(0.9428090415820635)
interShellF3 = 1.0
interShellF4 = np.float64(0.8660254037844387)
nAtomsF(i)

returns the number of atoms of an bcc rhombic dodecahedron of size i

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer, computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Computes the edge length of the nanoparticle in Å .

The edge length is determined based on the interatomic distance (Rnn) and the number of shells (nShell).

radiusCircumscribedSphere3()

Computes the radius of the circumscribed sphere at 3th order of the nanoparticle in Å.

radiusCircumscribedSphere4()

Computes the radius of the circumscribed sphere at 4th order of the nanoparticle in Å.

radiusMidSphere()

Computes the radius of the midsphere of the nanoparticle in Å. The midsphere is a sphere that touches the edges of the nanoparticle.

radiusInscribedSphere()

Computes the radius of the inscribed sphere of the nanoparticle in Å .

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of the dodecahedral nanoparticle. :param - i: Index of the shell :type - i: int

Returns:

The 14 vertex coordinates of the ith shell of an icosahedron - edges (np.ndarray): Indexes of the 24 edges - faces (np.ndarray): Indexes of the 12 faces

Return type:

  • CoordVertices (np.ndarray)

coords(noOutput)

Generates atomic coordinates for a tetrahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.catalanNPs.fccdrDD(element: str = 'Au', Rnn: float = 2.7, nShell: int = 1, **kwargs)

Bases: CatalanNP

A class for generating XYZ and CIF files of dihedral rhombic dodecahedral nanoparticles (NPs) of various sizes, based on user-defined compounds (either by name, e.g., “Fe”, “Au”, etc).

Key Features: - Allows to choose the NP size. - Can analyze the structure in detail, including symmetry and properties. - Offers options for core/surface differentiation based on a threshold. - Generates outputs in XYZ and CIF formats for visualization and simulations. - Provides compatibility with jMol for 3D visualization.

Additional Notes: - The symmetry analysis can be skipped to speed up computations. - Customizable precision thresholds for structural analysis.

Initialize the class with all necessary parameters.

Parameters:
  • element – Chemical element of the NP (e.g., “Au”, “Fe”).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • nShell (int) – Number of shells (e.g., nShell=1 means 2 atoms per edge).

  • postAnalyzis (bool) – If True, prints additional NP information. Examples: cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation. This is the distance threshold used to decide which atoms are retained.

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

self.shape

Shape ‘fccdrDD’

Type:

str

self.nAtoms

Number of atoms in the NP.

Type:

int

self.nAtomsPerShell

Number of atoms in each shell.

Type:

list

self.interShellDistance

Distance between shells.

Type:

float

self.jmolCrystalShape

Flag for JMol visualization.

Type:

bool

self.cog

Center of gravity of the NP.

Type:

np.array

self.imageFile

Path to a reference image.

Type:

str

nFaces = 12
nEdges = 32
nVertices = 14
edgeLengthF = 1
radiusCSF = 1
radiusCSFTB = np.float64(1.4142135623730951)
interShellF = 1.0
interShellFTB = np.float64(0.7071067811865475)
nAtomsF(i)

Returns the number of atoms of an bcc rhombic dodecahedron of size i

nAtomsPerShellAnalytic()

Computes the number of atoms per shell in an ordered nanoparticle.

The function iterates over each shell layer, computes the number of atoms for the given shell, and subtracts the cumulative sum of the previous shells to get the number of new atoms in the current shell.

Returns:

A list where each element represents the number of atoms

in a specific shell.

Return type:

list

nAtomsPerShellCumulativeAnalytic()

Computes the cumulative number of atoms up to each shell.

This function returns the total number of atoms present in the nanoparticle for each shell layer, building up cumulatively.

Returns:

A list where each element represents the total number of

atoms present up to that shell.

Return type:

list

nAtomsAnalytic()

Computes the total number of atoms in the nanoparticle.

edgeLength()

Computes the edge length of the nanoparticle in Å .

The edge length is determined based on the interatomic distance (Rnn) and the number of shells (nShell).

area()

Computes the surface area of the nanoparticle in square Ångströms.

volume()

Computes the volume of the nanoparticle in cubic Ångströms.

MakeVertices(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of the dodecahedral nanoparticle. :param - i: index of the shell :type - i: int

Returns:

the 14 vertex coordinates of the ith shell of a dihedral rhombic dodecahedron - edges (np.ndarray): indexes of the 24 edges - faces (np.ndarray): indexes of the 12 faces

Return type:

  • CoordVertices (np.ndarray)

coords(noOutput)

Generates atomic coordinates for a dodecahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display unit cell and nanoparticle properties.

johnsonNPs.py

class pyNanoMatBuilder.johnsonNPs.JohnsonNP(**kwargs)

Bases: pyNMBcore

Base class for all Johson nanoparticles providing common functionality.

Parameters:
  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation (distance threshold for retaining atoms).

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If False, generates the atomic structure of the NP.

class pyNanoMatBuilder.johnsonNPs.fcctbp(element: str = 'Au', Rnn: float = 2.7, nLayerTd: int = 1, **kwargs)

Bases: JohnsonNP

A class for generating fcc trigonal bipyramidal (fcctbp) nanoparticles (NPs) with a user-defined number of atomic layers and interatomic distances.

Key Features:

  • Generates a trigonal bipyramid shape with customizable atomic layers.

  • Computes structural properties like inter-layer distance, angles, and number of atoms.

  • Provides options for core/surface differentiation and symmetry analysis.

  • Supports visualization via ASE and Jmol for 3D structure representation.

Additional Notes:

  • The nLayerTd parameter determines the number of layers in one pyramid.

  • The Rnn parameter controls the nearest neighbor interatomic distance.

  • Symmetry analysis can be skipped to speed up computations.

  • Visualization can be enabled for both the initial structure and post-processing stages.

Initializes an fcc trigonal bipyramid (fcctbp) with the given parameters.

Parameters:
  • element (str) – Chemical element used to construct the NP (e.g., “Au”).

  • Rnn (float) – Nearest neighbor distance (in Å).

  • nLayerTd (int) – Number of atomic layers in each pyramid (default: 1).

  • postAnalyzis (bool) – If True, prints additional NP information (e.g., cell parameters, moments of inertia, inscribed/circumscribed sphere diameters, etc.).

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Threshold for core/surface classification (default: 1.0).

  • skipSymmetryAnalyzis (bool) – If False, performs symmetry analysis (default: False).

  • jmolCrystalShape (bool) – If True, generates a JMOL-compatible crystal shape (default: True).

  • noOutput (bool) – If True, suppresses text output (default: False).

  • calcPropOnly (bool) – If True, only calculates properties without generating structure (default: False).

nAtoms

Total number of atoms in the NP.

Type:

int

nAtomsPerLayer

Number of atoms in each atomic layer.

Type:

list

nAtomsPerEdge

Number of atoms per edge of the bipyramid.

Type:

int

interLayerDistance

Distance between atomic layers.

Type:

float

fveAngle

Face-vertex-edge angle.

Type:

float

fefAngle

Face-edge-face angle.

Type:

float

vcvAngle

Vertex-center-vertex angle.

Type:

float

heightOfBiPyramid

Height of the bipyramid.

Type:

float

imageFile

Path to the image representing the structure.

Type:

str

cog

Center of gravity of the NP.

Type:

np.array

trPlanes

Truncation plane equations.

Type:

np.array

nFaces = 6
nEdges = 9
nVertices = 5
edgeLengthF = 2
heightOfPyramidF = np.float64(1.632993161855452)
heightOfBiPyramidF = np.float64(3.265986323710904)
edgeLength()

Computes the edge length of the pyramids in Å using the class regfccTd of the Platonic module.

coords(noOutput)

Generates the coordinates of the fcc trigonal bipyramid.

First creates a regular fcc tetrahedron and then apply a mirror reflection to create the bipyramid. Calculates and centers the nanoparticle’s coordinates and finally computes the total number of atoms and the center of mass.

Parameters:

noOutput (bool) – Whether to suppress output messages.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.johnsonNPs.epbpyM(element: str = 'Au', Rnn: float = 2.7, sizeP: int = 1, sizeE: int = 0, Marks: int = 0, Multiples_index_plan: bool = False, Hollow: bool = False, **kwargs)

Bases: JohnsonNP

A class for generating pentagonal bipyramidal (epbpyM) nanoparticles (NPs) with a user-defined size.

Important note: the size must be carefully defined. It is represented as a three-element array, where:

  • The size of the pentagon (number of bonds per pentagonal edge),

  • The size of the elongated part (number of bonds per elongated edge),

  • The number of truncated atoms at the vertices (the number of truncated atoms per pentagonal edge is doubled since there are two vertices per edge).

Key Features:

  • Generates a trigonal bipyramid shape with customizable atomic layers.

  • Computes structural properties like inter-layer distance, angles, and number of atoms.

  • Provides options for core/surface differentiation and symmetry analysis.

  • Supports visualization via ASE and Jmol for 3D structure representation.

Additional Notes:

  • The user must ensure that the number of truncated atoms per edge is smaller than the number of atoms on the edges. An example of sizes is given.

  • Symmetry analysis can be skipped to speed up computations.

  • Visualization can be enabled for both the initial structure and post-processing stages.

Initialize the class with the necessary parameters.

Parameters:
  • element (str) – Chemical element (e.g., ‘Au’, ‘Fe’).

  • Rnn (float) – Nearest neighbor interatomic distance in Å.

  • sizeP (int) – Number of bonds per pentagonal edge, defining the size of the pentagon.

  • sizeE (int) – Number of bonds per elongated edge, defining the size of the elongated part.

  • Marks (int) – Number of truncated atoms at the vertices.

  • postAnalyzis (bool) – If True, performs post-analysis on the generated NP.

  • aseView (bool) – If True, visualizes the nanoparticle structure using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation.

  • skipSymmetryAnalyzis (bool) – If False, performs symmetry analysis on the structure.

  • jmolCrystalShape (bool) – If True, generates a Jmol script for visualization.

  • noOutput (bool) – If True, suppresses output.

  • calcPropOnly (bool) – If True, only calculates properties without generating the NP.

element

The chemical element.

Type:

str

shape

The shape (‘epbpyM’).

Type:

str

Rnn

Nearest neighbor interatomic distance.

Type:

float

sizeP

Number of bonds per pentagonal edge.

Type:

int

sizeE

Number of bonds per elongated edge.

Type:

int

Marks

Number of truncated atoms.

Type:

int

nAtoms

Total number of atoms.

Type:

int

nAtomsPerPentagonalCap

Atoms in the pentagonal caps.

Type:

int

nAtomsPerElongatedPart

Atoms in the elongated part.

Type:

int

nAtomsPerEdgeOfPC

Atoms per edge of the pentagonal cap (before truncation).

Type:

int

nAtomsPerEdgeOfEP

Atoms per edge of the elongated part.

Type:

int

jmolCrystalShape

Whether to generate a Jmol script for visualization.

Type:

bool

cog

Center of gravity (CoG).

Type:

np.array

interCompactPlanesDistance

Distance between compact planes.

Type:

float

imageFile

Path to the image file.

Type:

str

nFaces3 = 10
nFaces4 = 5
nEdgesPbpy = 15
nEdgesEpbpy = 20
nVerticesPbpy = 7
nVerticesEpbpy = 12
phi = np.float64(1.618033988749895)
edgeLengthF = 1
heightOfPyramidF = np.float64(0.5257311121191336)
interCompactPlanesF = np.float64(0.8090169943749475)
magicFactorF = np.float64(1.0514622242382672)
edgeLength(whichEdge)

Compute the edge length of pentagon and the elongated part in Å using Rnn and nAtomsPerEdgeOfPC / nAtomsPerEdgeOfEP.

nAtomsPerEdgeOfPC_after_truncation()

Compute the number of atoms per edge of the pentagon after truncation, using nAtomsPerEdgeOfPC and Marks.

edgeLength_after_truncation(whichEdge)

Compute the edge length of pentagon and the elongated part after truncation in Å, using Rnn, nAtomsPerEdgeOfPC / nAtomsPerEdgeOfEP and Marks.

area()

Compute the surface area in square Å.

volume()

Compute the volume in cubic Å.

heightOfPyramid()

Compute the height of the pyramid in Å.

MakeVertices()

Generate the coordinates of the vertices, edges, and faces of a pentagonal bipyramid.

Returns:

the 7 vertex

coordinates of a pentagonal dipyramid

edges (np.ndarray): indexes of the 2x5

”vertical” edges of the pentagonal cap of an elongated pentagonal bipyramid

faces (np.ndarray): indexes of the 10

triangular faces

Return type:

CoordVertices (np.ndarray)

truncationPlaneTuples4MarksDecahedron(refPlaneAtoms, debug=False)

Calculate the truncation planes for the Marks decahedron nanoparticle shape. It defines planes that truncate the vertices of the decahedron.

Parameters:
  • refPlaneAtoms (list) – A list of three atoms’ coordinates that define a reference plane. The list should contain: - summit atom (topmost point) - apex atom (the second point) - origin atom (used as reference)

  • debug (bool) – flag to enable or disable debugging information (default is False).

Returns:

An array of 5 planes

used for truncation, each defined by a normal vector and an offset.

indicesOfTruncationPlanes (list): A list of

tuples, each containing two indices that define the truncation plane pairs.

Return type:

planes (array-like)

coords(noOutput)

Generate coordinates of all atoms in the nanoparticle structure, including vertices, edges, faces, and internal atoms. Applies truncation and symmetry operations where necessary.

Parameters:

noOutput (bool) – if True, suppresses output messages during execution.

Returns:

None. Updates class attributes directly.

prop()

Display unit cell and nanoparticle properties.

class pyNanoMatBuilder.johnsonNPs.eOhM(element: str = 'Au', Rnn: float = 2.88, nOrder: int = 1, wire_length: int = 0, wire_width: int = None, Marks_110: int = 0, Marks_100: int = 0, Marks_on_wire_only: bool = False, **kwargs)

Bases: JohnsonNP

A class for generating elongated fcc octahedral (eOhM) nanoparticles with optional Marks-like truncation of the vertical edges.

Inherits from regfccOh and extends it with:

  • Elongation along [001] (Ino-like) via sizeE parameter, where each sizeE unit corresponds to one fcc unit cell along [001].

  • Marks truncation of vertical <110> edges via Marks parameter.

The octahedron has 8 {111} faces. Elongation adds 4 {100} square faces between the two equatorial crowns. Marks truncation adds {110} facets on the vertical edges.

Key Features:

  • Generates an elongated octahedron with customizable atomic layers.

  • Computes structural properties like inter-plane distance, edge length, area, volume, and total height.

  • Provides options for core/surface differentiation and symmetry analysis.

  • Supports visualization via ASE and Jmol for 3D structure representation.

Additional Notes:

  • The user must ensure that the number of truncated atoms on the vertical edges is smaller than the number of atoms on the edges.

  • Symmetry analysis can be skipped to speed up computations.

  • Marks truncation is not yet implemented (TODO).

Initialize the class with the necessary parameters.

Parameters:
  • element (str) – Chemical element (e.g., ‘Au’, ‘Fe’).

  • Rnn (float) – Nearest-neighbor interatomic distance in Å. Default is 2.88 (Au fcc).

  • nOrder (int) – Number of atomic layers along an edge of the octahedron (e.g., nOrder=1 means 2 atoms per edge). Default is 1.

  • wire_length (int) – Number of fcc unit cells along [001] separating the two equatorial crowns. Default is 0 (regular octahedron).

  • wire_width – width of the wire. If None, will be initialized as nOrder. wire_width < nOrder will make a double arrow

  • Marks (int) – Number of truncated atoms on vertical <110> edges . Default is 0.

  • Marks_on_wire_only (bool) – Apply the Marks-like truncation on the wire only (Default: False).

  • postAnalyzis (bool) – If True, performs post-analysis on the generated NP.

  • aseView (bool) – If True, visualizes the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation.

  • skipSymmetryAnalyzis (bool) – If False, performs symmetry analysis.

  • jmolCrystalShape (bool) – If True, generates a Jmol script.

  • noOutput (bool) – If True, suppresses output.

  • calcPropOnly (bool) – If True, only calculates properties without generating the NP.

element

The chemical element.

Type:

str

shape

The shape (‘eOhM’).

Type:

str

Rnn

Nearest-neighbor distance.

Type:

float

nOrder

Atomic layers along edge.

Type:

int

wire_length

Elongation in fcc (1,0,0) unit cells.

Type:

int

Marks

Number of truncated atoms.

Type:

int

nAtoms

Total number of atoms.

Type:

int

interCompactPlanesDistance_111

d{111} in Å.

Type:

float

interCompactPlanesDistance_100

d{100} in Å.

Type:

float

cog

Center of gravity.

Type:

np.array

imageFile

Path to the reference image.

Type:

str

nEdges = 8
nFaces3 = 4
nFaces4 = 1
nVertices = 5
nEdges_Oh = 12
nFaces3_Oh = 4
nFaces4_Oh = 8
nVertices_Oh = 6
nEdges_eOh = 20
nFaces3_eOh = 8
nFaces4_eOh = 4
nVertices_eOh = 10
edgeLengthF = 1
intershellF = np.float64(1.4142135623730951)
halfHeightF = np.float64(0.7071067811865475)
interCompactPlanesF_111 = np.float64(0.816496580927726)
interCompactPlanesF_110 = 1.0
interCompactPlanesF_100 = np.float64(1.4142135623730951)
interCompactPlanesF_001 = np.float64(1.4142135623730951)
edgeLength()

Compute the octahedral edge length in Å.

Octahedral edges lie along <110> in fcc, so their length equals nOrder * Rnn.

Returns:

Edge length in Å.

Return type:

float

halfHeightPyramid()

Compute the half-height of one pyramidal cap along [001] in Å.

For a regular octahedron of edge length L, the half-height equals L / sqrt(2).

Returns:

Half-height of one cap in Å.

Return type:

float

elongationLength()

Compute the total length of the elongated part along [001] in Å.

Each elongation unit corresponds to one fcc unit cell along [001], i.e. a = Rnn * sqrt(2). The two crowns are separated by wire_length * a.

Returns:

Elongation length in Å.

Return type:

float

totalHeight()

Compute the total height of the eOhM nanoparticle along [001] in Å.

Equals twice the pyramidal cap half-height plus the elongation length.

Returns:

Total height in Å.

Return type:

float

area()

Compute the surface area of the eOhM nanoparticle in square Å.

Contributions: - 8 equilateral triangular {111} faces of edge length L. - 4 rectangular {100} faces of dimensions L × elongationLength

(only when wire_length > 0).

Returns:

Surface area in Ų.

Return type:

float

volume()

Compute the volume of the eOhM nanoparticle in cubic Å.

Contributions: - Regular octahedron of edge length L: V = sqrt(2)/3 * L³. - Square prism of section L² and height elongationLength

(only when wire_length > 0).

Returns:

Volume in ų.

Return type:

float

edge_atom_index(n, k, nEdges)

Return the index in the coordinate list c of the atom located at level n on edge E[k].

Edge atoms in c are stored sequentially:
for n in range(nAtomsOnEdges):
for k in range(nEdges):

append atom on edge E[k] at level n

Therefore the atom on edge E[k] at level n is at index:

nVertices + n * nEdges + k

Parameters:
  • n (int) – Level along the edge (0 = closest to start vertex, nAtomsOnEdges-1 = closest to end vertex).

  • k (int) – Edge index in the edge list E.

  • nEdges (int) – Total number of edges (= len(E)).

Returns:

Index in the coordinate list c.

Return type:

int

MakeVertices_SquarePyramid(i)

Generates the coordinates of the vertices, edges, and faces for the ith shell of a square pyramid nanoparticle.

Parameters:

i (int) – Index of the shell layer.

Returns:

  • CoordVertices (np.ndarray): the 6 vertex coordinates

    of the ith shell of an octahedron

  • edges (np.ndarray): indexes of the 30 edges

  • faces (np.ndarray): indexes of the 20 faces

Return type:

tuple

truncationPlanes4MarksOctahedron(debug=False)

Calculate the 8 truncation planes for the Marks-like octahedron: - 4 {110} planes cutting the vertical corners of the wire - 4 {100} planes cutting the vertical faces of the wire Both sets are rotated by 90° around [001].

Parameters:

debug (bool) – If True, prints debug information.

Returns:

Array of 8 truncation planes [h,k,l,d]. indicesOfTruncationPlanes (list): List of plane index pairs

used for truncation.

Return type:

planes (np.ndarray)

coords(noOutput)

Generates atomic coordinates for an octahedral nanoparticle.

Parameters:

noOutput (bool) – If False, displays progress and timing information.

Steps:
  • Generates vertex atoms.

  • Calculates and places edge atoms along the edges.

  • Generates facet atoms to fill in faces.

  • Adds core atoms layer by layer.

  • Stores final atomic positions in an ASE Atoms object.

Returns:

None (updates class attributes).

prop()

Display geometric properties of the nanoparticle.

otherNPs.py

class pyNanoMatBuilder.otherNPs.fcctpt(element: str = 'Au', Rnn: float = 2.7, nLayerTd: int = 1, nLayer: int = 3, **kwargs)

Bases: pyNMBcore

This class generates and manages the properties of an fcc triangular platelet, which is based on a trigonal bipyramid structure. It provides methods to calculate and manipulate atomic coordinates, compute the properties of the nanoparticle, and generate visualizations.

Initializes the fcc triangular platelet nanoparticle.

Parameters:
  • element (str) – The element of the nanoparticle (default ‘Au’).

  • Rnn (float) – The nearest neighbor distance (default 2.7 Å).

  • nLayerTd (int) – Number of layers (bonds per edge) of the two tetrahedrons used to create the platelet. This value will define the edge length of the final platelet; the number of layers of the platelet will be nLayerTd + 1.

  • nLayer (int) – The number of layers kept for each tetrahedron (not counting the twin plane). This value will define the thickness of the platelet; the number of layers in the final platelet will be nLayer * 2.

  • postAnalyzis (bool) – If True, prints additional NP information.

  • aseView (bool) – If True, enables visualization of the NP using ASE.

  • thresholdCoreSurface (float) – Precision threshold for core/surface differentiation.

  • skipSymmetryAnalyzis (bool) – If False, performs an atomic structure analysis using pymatgen.

  • jmolCrystalShape (bool) – If True, generates a JMOL script for visualization.

  • noOutput (bool) – If False, prints details about the NP structure.

  • calcPropOnly (bool) – If True, enables visualization of the NP using ASE.

nFaces

The number of faces of the triangular platelet.

Type:

int

nEdges

The number of edges of the triangular platelet.

Type:

int

nVertices

The number of vertices of the triangular platelet.

Type:

int

edgeLengthF

A factor for edge length.

Type:

float

element

The chemical element for the nanoparticle.

Type:

str

shape

The shape of the nanoparticle (‘fcctpt’).

Type:

str

Rnn

The nearest neighbor distance in Angstroms.

Type:

float

nLayerTd

Number of layers (bonds per edge) of the two tetrahedrons used to create the platelet.

Type:

int

nLayer

The number of layers kept for each tetrahedron.

Type:

int

nAtoms

Number of atoms in the nanoparticle.

Type:

int

interLayerDistance

Distance between layers.

Type:

float

nAtomsPerEdge

Number of atoms per edge at the twin boundary.

Type:

int

cog

Center of gravity of the nanoparticle.

Type:

np.array

dim

Dimensions of the nanoparticle.

Type:

list

jmolCrystalShape

Flag to indicate whether to display the crystal shape in Jmol.

Type:

bool

imageFile

Path to the image file of the nanoparticle shape.

Type:

str

nFaces = 8
nEdges = 9
nVertices = 9
edgeLengthF = 2
edgeLength()

Computes the edge length of the triangular platelet in Å..

coords(noOutput)

Generates the coordinates of the triangular platelet nanoparticle.

This method creates the atomic positions by truncating a trigonal bipyramid and adjusting the coordinates based on the twin and truncation planes.

Parameters:

noOutput (bool) – Whether to suppress output messages.

prop()

Display unit cell and nanoparticle properties.

Utilities (utils/)

core functions (core.py)

class pyNanoMatBuilder.utils.core.fg

Bases: object

PURPLE = '\x1b[95m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
BLUE = '\x1b[94m'
GREEN = '\x1b[92m'
YELLOW = '\x1b[93m'
RED = '\x1b[91m'
LIGHTGRAY = '\x1b[37m'
DARKGRAY = '\x1b[90m'
BLACK = '\x1b[30m'
WHITE = '\x1b[38;5;231m'
OFF = '\x1b[0m'
class pyNanoMatBuilder.utils.core.hl

Bases: object

BOLD = '\x1b[1m'
bold = '\x1b[21m'
UNDERL = '\x1b[4m'
underl = '\x1b[24m'
ITALIC = '\x1b[3m'
italic = '\x1b[23m'
OFF = '\x1b[0m'
class pyNanoMatBuilder.utils.core.bg

Bases: object

DARKRED = '\x1b[38;5;231;48;5;52m'
DARKREDB = '\x1b[38;5;231;48;5;52;1m'
LIGHTRED = '\x1b[48;5;217m'
LIGHTREDB = '\x1b[48;5;217;1m'
LIGHTYELLOW = '\x1b[48;5;228m'
LIGHTYELLOWB = '\x1b[48;5;228;1m'
LIGHTGREEN = '\x1b[48;5;156m'
LIGHTGREENB = '\x1b[48;5;156;1m'
LIGHTBLUE = '\x1b[48;5;117m'
LIGHTBLUEB = '\x1b[48;5;117;1m'
OFF = '\x1b[0m'
class pyNanoMatBuilder.utils.core.color

Bases: object

PURPLE = '\x1b[95m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
BLUE = '\x1b[94m'
GREEN = '\x1b[92m'
YELLOW = '\x1b[93m'
RED = '\x1b[91m'
LIGHTGRAY = '\x1b[37m'
DARKGRAY = '\x1b[90m'
BLACK = '\x1b[30m'
WHITE = '\x1b[38;5;231m'
BOLD = '\x1b[1m'
OFF = '\x1b[0m'
pyNanoMatBuilder.utils.core.pyNMB_location()

Returns the absolute path to the root of the installed package.

pyNanoMatBuilder.utils.core.get_resource_path(sub_folder: str, filename: str) str

Retrieve the absolute path of a resource file within the package.

This helper uses the modern ‘importlib.resources.files’ API (Python 3.9+) to ensure compatibility with various installation environments like Google Colab or virtual environments.

Parameters:
  • sub_folder (str) – Folder path relative to the package root (e.g., ‘resources/figs’ or ‘resources/cif_database’).

  • filename (str) – Name of the file (e.g., ‘banner.png’).

Returns:

The absolute string path to the file.

Return type:

str

class pyNanoMatBuilder.utils.core.timer

Bases: object

Timer class to measure elapsed time in seconds and display it in hh:mm:ss ms.

hdelay_ms(delay)

Converts a delay into a human-readable format: hh:mm:ss ms.

Parameters:

delay – A timedelta object or a float representing a duration in seconds.

Returns:

mm:ss ms.

Return type:

A formatted string in hh

chrono_start()

Starts the chrono.

chrono_stop(hdelay=False)

Stops the chrono and returns the elapsed time.

chrono_show()

Prints the elapsed time.

pyNanoMatBuilder.utils.core.RAB(coord, a, b)

Calculate the distance between two atoms by indices.

Parameters:
  • coord (array-like) – Array of 3D coordinates.

  • a (int) – Index of the first atom.

  • b (int) – Index of the second atom.

Returns:

Distance between atoms a and b.

Return type:

float

pyNanoMatBuilder.utils.core.Rbetween2Points(p1, p2)

Calculate the distance between two points.

Parameters:
  • p1 (array-like) – 3D coordinates of the first point.

  • p2 (array-like) – 3D coordinates of the second point.

Returns:

Distance between p1 and p2.

Return type:

float

pyNanoMatBuilder.utils.core.vector(coord, a, b)

Compute the vector from point a to point b given a list of coordinates.

Parameters:
  • coord (array-like) – Array of 3D coordinates.

  • a (int) – Index of the starting point.

  • b (int) – Index of the ending point.

Returns:

Vector from a to b.

Return type:

np.ndarray

pyNanoMatBuilder.utils.core.vectorBetween2Points(p1, p2)

Compute the vector between two 3D points.

Parameters:
  • p1 (array-like) – 3D coordinates of the first point.

  • p2 (array-like) – 3D coordinates of the second point.

Returns:

Vector from p1 to p2.

Return type:

np.ndarray

pyNanoMatBuilder.utils.core.coord2xyz(coord)

Extracts x, y, and z from a list of 3D coordinates.

Parameters:
  • [[x1 (A list or array of 3D coordinates in the format)

  • y1

  • z1]

  • [x2

  • y2

  • z2]

  • ...].

Returns:

Three NumPy arrays containing the x, y, and z coordinates separately.

pyNanoMatBuilder.utils.core.vertex(x, y, z, scale)

Return vertex coordinates fixed to the unit sphere.

pyNanoMatBuilder.utils.core.vertexScaled(x, y, z, scale)

Return vertex coordinates multiplied by the scale factor.

pyNanoMatBuilder.utils.core.RadiusSphereAfterV(V)

Computes the radius of a sphere given its volume.

Parameters:

V (float) – Volume of the sphere in cubic units.

Returns:

Radius of the sphere.

Return type:

float

Formula: R = (3V / (4π))^(1/3)

pyNanoMatBuilder.utils.core.centerOfGravity(c: ndarray, select=None)

Compute center of gravity of selected atoms.

pyNanoMatBuilder.utils.core.center2cog(c: ndarray)

Centers a set of atomic coordinates to their center of gravity.

Parameters:

c (np.ndarray) – An array of shape (N, 3) representing N atomic positions (x, y, z).

Returns:

A new array of centered coordinates where the center of gravity is at (0,0,0).

Return type:

np.ndarray

Notes: - Uses centerOfGravity(c) to compute the center of gravity. - Each atomic position is shifted by subtracting the center of gravity.

pyNanoMatBuilder.utils.core.normOfV(V)

Returns the norm of a vector V. :param V: A 3-element array representing a vector [Vx, Vy, Vz]. :type V: np.ndarray

Returns:

The norm of the vector.

Return type:

float

pyNanoMatBuilder.utils.core.normV(V)

Computes the normalized unit vector of a vector V. :param V: A 3-element array representing a vector [Vx, Vy, Vz]. :type V: np.ndarray

Returns:

A 3-element array representing the normalized vector.

Return type:

np.ndarray

pyNanoMatBuilder.utils.core.AngleBetweenVV(lineDV, planeNV)

Return the angle, in degrees, between two vectors.

pyNanoMatBuilder.utils.core.signedAngleBetweenVV(v1, v2, n)

Return the signed angle between two vectors in degrees in [0, 360].

Parameters:
  • v1 (np.ndarray) – First vector.

  • v2 (np.ndarray) – Second vector.

  • n (np.ndarray) – Normal of the plane formed by the two vectors.

Returns:

Signed angle in degrees.

Return type:

float

pyNanoMatBuilder.utils.core.centerToVertices(coordVertices: ndarray, cog: ndarray)

Computes the vectors and distances between the center of gravity (cog) and each vertex of a polyhedron. :param coordVertices: Array of shape (n_vertices, 3) containing the coordinates of the vertices. :type coordVertices: np.ndarray :param cog: A 3-element array representing the center of gravity of the nanoparticle. :type cog: np.ndarray

Returns:

  • directions (np.ndarray): Array of shape (n_vertices, 3) containing the vectors from cog to each vertex.

  • distances (np.ndarray): Array of shape (n_vertices,) containing the distances from cog to each vertex.

Return type:

tuple

pyNanoMatBuilder.utils.core.Rx(a)

Return the R/x rotation matrix.

pyNanoMatBuilder.utils.core.Ry(a)

Return the R/y rotation matrix.

pyNanoMatBuilder.utils.core.Rz(a)

Return the R/z rotation matrix.

pyNanoMatBuilder.utils.core.EulerRotationMatrix(gamma, beta, alpha, order='zyx')

Return a 3x3 Euler rotation matrix.

Parameters:
  • gamma – Rot/x (°).

  • beta – Rot/y (°).

  • alpha – Rot/z (°).

  • order – If (order=”zyx”): returns Rz(alpha) * Ry(beta) * Rx(gamma).

Returns:

A 3x3 Euler matrix.

Return type:

np.ndarray

pyNanoMatBuilder.utils.core.plotPalette(Pcolors, namePC, angle=0, savePngAs=None)

Plot a 1D palette of colors with names.

Parameters:
  • Pcolors – 1D list with hex colors.

  • namePC – Label for each color.

  • angle – Rotation angle of the text.

  • savePngAs – Also saves the palette in a png file (default: None).

pyNanoMatBuilder.utils.core.rgb2hex(c, frac=True)

Convert an RGB color to its hexadecimal representation.

It has an optional frac argument to handle the case where the RGB values are provided as fractions (ranging from 0 to 1) or as integers (ranging from 0 to 255).

Parameters:
  • c – RGB color tuple.

  • frac (bool) – If True, RGB values are fractions (0-1).

Returns:

Hexadecimal representation.

Return type:

str

pyNanoMatBuilder.utils.core.clone(system)

Create and return a deep copy of any pyNanoMatBuilder system.

This ensures that all internal arrays, ASE atoms objects, and Pymatgen structures are fully independent from the original.

Parameters:

system – A pyNanoMatBuilder object (e.g., Crystal, Icosahedron).

Returns:

A completely independent clone of the input system.

pyNanoMatBuilder.utils.core.deleteElementsOfAList(t, list2Delete: bool)

Return a new list with elements deleted based on a boolean mask.

Parameters:
  • t – List or array-like.

  • list2Delete (bool) – Boolean mask, list2Delete[i] = True deletes t[i].

Returns:

Filtered list.

Return type:

list

pyNanoMatBuilder.utils.core.centerTitle(content=None)

Centers and renders as HTML a text in the notebook font size = 16px, background color = dark grey, foreground color = white

pyNanoMatBuilder.utils.core.centertxt(content=None, font='sans', size=12, weight='normal', bgc='#000000', fgc='#ffffff')

Centers and renders as HTML a text in the notebook

input:
  • content = the text to render (default: None)

  • font = font family (default: ‘sans’, values allowed = ‘sans-serif’ | ‘serif’ | ‘monospace’ | ‘cursive’ | ‘fantasy’ | …)

  • size = font size (default: 12)

  • weight = font weight (default: ‘normal’, values allowed = ‘normal’ | ‘bold’ | ‘bolder’ | ‘lighter’ | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 )

  • bgc = background color (name or hex code, default = ‘#ffffff’)

  • fgc = foreground color (name or hex code, default = ‘#000000’)

pyNanoMatBuilder.utils.core.planeFittingLSF(coords: float64, printErrors: bool = False, printEq: bool = True)

Least-square fitting of the equation of a plane ux + vy + wz + h = 0 that passes as close as possible to a set of 3D points :param - coords: array with shape (N,3) that contains the 3 coordinates for each of the N points :type - coords: np.ndarray :param - printErrors: if True, prints the absolute error between the actual z coordinate of each points :type - printErrors: bool :param and the corresponding z-value calculated from the plane equation. The residue is also printed: :param - printEq: if True, prints equation. :type - printEq: bool

Returns:

numpy array([u v w h])

pyNanoMatBuilder.utils.core.faces_to_planes(faces, coords)

Converts a list of faces in planes equations [u, v, w, d].

Parameters:
  • faces (list of tuples) – List of faces [(i, j, k)] with the vertices indexes.

  • coords (np.ndarray) – Atoms coordinates.

Returns:

List of planes equations

[u, v, w, d].

Return type:

planes (list of np.ndarray)

pyNanoMatBuilder.utils.core.round_to_Miller(planes_float, tol=0.1, debug=False)

Convert float plane normals to nearest integer Miller indices. Normalizes by the minimum non-zero absolute value across all planes, ensuring a consistent common factor for rotation-generated families.

Parameters:
  • planes_float (array-like) – Float plane normals, shape (N, 3).

  • tol (float) – Maximum allowed rounding error per index. Default is 0.1.

  • debug (bool) – print warning messages if rounding error exceeds tolerance Default is False

Returns:

Integer Miller indices, shape (N, 3). bool: True if all indices are within tolerance for all planes.

Return type:

np.ndarray

pyNanoMatBuilder.utils.core.kDTreeCN(crystal: Atoms, Rmax: float = 2.9, returnD: bool = False, noOutput: bool = False)

Return the nearest neighbour (nn) table and number of NN per atom.

Parameters:
  • crystal (Atoms) – Crystal structure object.

  • Rmax (float) – The NN threshold.

  • returnD (bool) – If True, distances between NN are returned as well.

  • noOutput (bool) – If True, suppresses output messages.

Returns:

(nn, CN) or (nn, CN, dNN) if returnD is True.

Return type:

tuple

Geometry Tools (geometry.py)

pyNanoMatBuilder.utils.geometry.MakeFaceCoord(Rnn, f, coord, nAtomsOnFaces, coordFaceAt)

Interpolates atom positions on a given face of a polyhedron by distributing atoms between two relevant edges.

Parameters:
  • Rnn (float) – Nearest neighbor distance.

  • f (list) – List of vertex indices defining the face.

  • coord (np.ndarray) – Array containing the coordinates of all atoms.

  • nAtomsOnFaces (int) – Counter for the number of atoms placed on faces.

  • coordFaceAt (list) – List of face atom coordinates to be updated.

Returns:

  • nAtomsOnFaces (int): Updated count of face atoms.

  • coordFaceAt (list): Updated list of coordinates of atoms placed on faces.

Return type:

tuple

Method:
  1. Determines two relevant edges based on the number of vertices in the face.

  2. Interpolates atoms along these edges.

  3. Fills the face by interpolating between interpolated edge atoms.

pyNanoMatBuilder.utils.geometry.reduceHullFacets(self, noOutput: bool = False, tolAngle: float = 2.0, useWulff: bool = False)

Reduce crystal facets based on convex hull and coplanarit of facets.

Parameters:
  • noOutput (bool) – If True, suppresses output to the console. Default is False.

  • tolAngle (float) – Tolerance angle to define coplanarity. Default is 2.0 degree.

  • useWulff (bool) – If True, uses the Wulff construction planes (trPlanes_Wulff) regardless of whether the structure is optimized or not. If False, uses trPlanes_opt for optimized structures, or trPlanes for initial structures. Default is True.

Returns:

The vertices and reduced faces.

Return type:

tuple

Note

  • Previous hull.simplices must have been saved as Crystal.trPlanes.

  • trPlanes_wWlff must have been saved during the Wulff construction. The result is always saved in self.trPlanes (or self.trPlanes_opt).

pyNanoMatBuilder.utils.geometry.RotationMol(coords, angle, axis='z')

Perform a rotation of the molecule’s coordinates around a specified axis.

Parameters:
  • coords (numpy.ndarray) – Coordinates of the molecule as a matrix (n x 3).

  • angle (float) – The angle of rotation in degrees.

  • axis (str) – The axis around which to perform the rotation (‘x’, ‘y’, or ‘z’).

Returns:

R[0] The coordinates of the molecule after rotation, as a matrix (n x 3).

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.geometry.EulerRotationMol(coords, gamma, beta, alpha, order='zyx')

Perform an Euler rotation of the molecule’s coordinates.

Parameters:
  • coords (numpy.ndarray) – Coordinates of the molecule as a matrix (n x 3).

  • gamma (float) – Angle gamma in degrees.

  • beta (float) – Angle beta in degrees.

  • alpha (float) – Angle alpha in degrees.

  • order (str) – The order of the Euler rotations (default is “zyx”).

Returns:

The coordinates of the molecule after the Euler rotation, as a matrix (n x 3).

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.geometry.RotationMatrixFromAxisAngle(u, angle)

Generates a 3x3 rotation matrix from a unit vector representing the axis of rotation and a rotation angle. :param u: A unit vector representing the axis of rotation (3 elements). :type u: numpy.ndarray :param angle: The angle of rotation in degrees. :type angle: float

Returns:

A 3x3 rotation matrix.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.geometry.rotationMolAroundAxis(coords, angle, axis)

Return coordinates after rotation by a given angle around an [u,v,w] axis.

Parameters:
  • coords – natoms x 3 numpy array.

  • angle – Angle of rotation.

  • axis – Directions given under the form [u,v,w].

Returns:

Rotated coordinates.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.geometry.rotation_around_axis_through_point(coords, angle_deg, axis, center)

Rotate coords (n,3) around a given axis (3,) passing through a point center (3,) by a given angle (in degrees).

pyNanoMatBuilder.utils.geometry.reflection(plane, points, doItForAtomsThatLieInTheReflectionPlane=False, eps=0.01)

Apply a mirror-image symmetry operation to an array of points.

Calculates the reflection of each point across a symmetry plane defined by the general equation $ax + by + cz + d = 0$.

Parameters:
  • plane (list or numpy.ndarray) – The four parameters $[a, b, c, d]$ that define the reflection plane equation.

  • points (numpy.ndarray) – An (N, 3) array of Cartesian coordinates representing the points to be reflected.

  • doItForAtomsThatLieInTheReflectionPlane (bool, optional) – If True, points located exactly on the reflection plane +- eps are processed. If False, they are skipped. Defaults to False.

  • (float (eps) – 1e-2): threshold associated to doItForAtomsThatLieInTheReflectionPlane

  • default – 1e-2): threshold associated to doItForAtomsThatLieInTheReflectionPlane

Returns:

An (N, 3) array containing the coordinates of the reflected mirror-image points.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.geometry.reflection_with_face_update(plane, points, faces, current_indices, eps=0.01, debug=False)

Apply a reflection to a set of points across a plane while mapping indices.

This function identifies points lying on the reflection plane (shared atoms) and those to be reflected (new atoms). Instead of duplicating shared atoms, it maps their local indices to their existing global indices in the assembly. New atoms are marked with a “NEW” placeholder to be indexed in the global coordinate array later.

Parameters:
  • plane (np.ndarray) – Plane equation [a, b, c, d] for ax + by + cz + d = 0.

  • points (np.ndarray) – (N, 3) Cartesian coordinates of the current unit.

  • faces (list of tuples) – Local face definitions (vertex indices).

  • current_indices (list of int) – Global indices in all_coords for each point in points.

  • eps (float) – Distance threshold to consider a point as lying on the plane. Defaults to 1e-2.

  • debug (bool) – If True, prints mapping information. Defaults to False.

Returns:

  • reflected_points (np.ndarray): Coordinates of the truly new atoms.

  • old_to_new (dict): Dictionary mapping local indices (0 to N-1) to either a global integer index or the string “NEW”.

Return type:

tuple

pyNanoMatBuilder.utils.geometry.helical_assembly(seed_coords, seed_faces, n_units, face_sequence=None, eps=0.01, debug=False)

Generate a helical assembly of polyhedra via successive face reflections.

This engine builds complex structures (like the Boerdijk-Coxeter helix) by reflecting a seed unit across its faces. It prevents atomic duplication by tracking global indices and only adding “new” vertices to the coordinate array at each step.

Parameters:
  • seed_coords (np.ndarray) – (N, 3) coordinates of the initial polyhedral unit (e.g., a tetrahedron).

  • seed_faces (list of tuples) – Vertex index tuples defining the faces of the seed unit.

  • n_units (int) – Total number of polyhedral units to assemble.

  • face_sequence (list of int, optional) – Sequence of face indices to cycle through for reflections. Defaults to range(len(seed_faces)).

  • eps (float) – Precision threshold for detecting atoms on the reflection plane. Defaults to 1e-2.

  • debug (bool) – If True, prints step-by-step assembly logs and updated global face indices. Defaults to False.

Returns:

  • all_coords (np.ndarray): (M, 3) array of all distinct atomic coordinates in the final helix.

  • n_atoms (int): Total number of unique atoms (M).

Return type:

tuple

Notes

The function maintains a ‘current_global_indices’ list to ensure topological continuity between successive units without using nearest-neighbor searches (like KDTree).

pyNanoMatBuilder.utils.geometry.reflection_tetra(plane, points)

Simplified reflection function for the helix of tetrahedrons.

Parameters:
  • plane – [u,v,w,d] parameters that define a plane.

  • points – (N, 3) array of points.

Returns:

(N, 3) array of reflected points.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.remove_duplicate_atoms(coordinates, reference_coords, tolerance)

Robustly removes duplicate atoms from coordinates using adaptive tolerance.

Identifies atoms in ‘coordinates’ that are within ‘tolerance’ of any atom in ‘reference_coords’ and removes them. This is ideal for removing atoms added by reflection that already exist on shared faces.

Parameters:
  • coordinates (np.ndarray) – (N, 3) array of new atoms to filter

  • reference_coords (np.ndarray) – (M, 3) array of existing atoms (reference)

  • tolerance (float) – Distance threshold for duplicate detection. Recommended: 0.1 * Rnn for molecular structures.

Returns:

(unique_coords, n_removed)
  • unique_coords: (K, 3) filtered coordinates

  • n_removed: (int) number of duplicates removed

Return type:

tuple

Notes

  • Atoms from ‘coordinates’ that are far from all atoms in ‘reference_coords’ are considered unique and kept.

  • Efficiency: O(N*M) where N=len(coordinates), M=len(reference_coords)

  • Use this when adding incrementally to existing structure (helix generation)

Example

>>> new_atoms = np.array([[0.5, 0, 0], [5, 0, 0]])
>>> existing = np.array([[0, 0, 0], [1, 0, 0]])
>>> tol = 0.1
>>> unique, n_dup = remove_duplicate_atoms(new_atoms, existing, tol)
>>> print(n_dup)  # 1 (first atom is duplicate)
pyNanoMatBuilder.utils.geometry.planeRotation(Crystal, refPlane, rotAxis, nRot=6, returnMiller: bool = False, debug: bool = False, noOutput: bool = False)

Return planes obtained by rotating a reference plane around an axis, expressed in Cartesian coordinates.

Parameters:
  • Crystal – pyNanoMatBuilder object.

  • refPlane (array-like) – Reference plane in Miller indices [h, k, l] to be rotated.

  • rotAxis (array-like) – Rotation axis in crystallographic coordinates [u, v, w].

  • nRot (int) – Number of rotations. The rotation angle is 360°/nRot. Default is 6.

  • returnMiller (bool) – If True, also returns the rotated planes expressed as Miller indices in the crystallographic basis. Default is False.

  • debug (bool) – If True, prints normalized plane normals in both Cartesian and Miller index representations. Default is False.

  • noOutput (bool) – If True, suppresses all output. Default is False.

Returns:

Array of shape (nRot, 3) containing the rotated plane

normals in Cartesian coordinates.

np.ndarray (optional): Array of shape (nRot, 3) containing the

rotated plane normals as Miller indices in the crystallographic basis. Only returned if returnMiller=True.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.alignV1WithV2_returnR(v1, v2=array([0, 0, 1]))

Return the rotation matrix that aligns v1 with v2.

Parameters:
  • v1 (np.ndarray) – Source vector.

  • v2 (np.ndarray) – Target vector.

Returns:

3x3 rotation matrix.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.rotateMoltoAlignItWithAxis(coords, axis, targetAxis=array([0, 0, 1]))

Return coordinates after rotation aligning axis with targetAxis.

Parameters:
  • coords (np.ndarray) – (n_atoms, 3) array of coordinates.

  • axis (np.ndarray) – Axis direction [u, v, w].

  • targetAxis (np.ndarray) – Target axis direction.

Returns:

Rotated coordinates (n_atoms, 3).

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.setdAsNegative(planes)

Flip plane signs so that d is negative.

Parameters:

planes (np.ndarray) – Array of planes.

Returns:

Updated planes.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.returnPlaneParallel2Line(V, shift=[1, 0, 0], debug=False)

Return plane parameters for a plane parallel to a direction vector.

Parameters:
  • V (np.ndarray) – Direction vector.

  • shift (list) – Shift vector used to build an arbitrary non-parallel vector.

  • debug (bool) – If True, prints intermediate values.

Returns:

Plane normal [a, b, c]; d must be found separately.

Return type:

np.ndarray

Method:

  • choose any arbitrary vector not parallel to V[i,j,k] such as V[i+1,j,k]

  • calculate the vector perpendicular to both of these, i.e. the cross product

  • this is the normal to the plane, i.e. you directly obtain the equation of the plane ax+by+cz+d = 0, d being indeterminate (to find d, it would be necessary to provide an (x0,y0,z0) point that does not belong to the line, hence d = -ax0-by0-cz0)

pyNanoMatBuilder.utils.geometry.normal2MillerPlane(Crystal, MillerIndexes, printN=True)

Return the normal direction to the plane defined by h,k,l Miller indices defined as [n1 n2 n3] = (hkl) x G*, where G* is the reciprocal metric tensor (G* = G-1). convertuvwh2hkld() function applied here converts real plane indexes to integers.

Parameters:
  • Crystal – Crystal object with G*.

  • MillerIndexes (np.ndarray) – Miller indices [h, k, l].

  • printN (bool) – If True, prints the computed normals.

Returns:

Integer-normalized plane normal.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.isPlaneParrallel2Line(v1, v2, tol=1e-05)

Return True if line direction and plane normal are parallel. A line direction vector and a plane are parallel if $|angle|$ between the line and the normal vector of the plane is 90°.

Parameters:
  • v1 (np.ndarray) – Line direction vector.

  • v2 (np.ndarray) – Plane normal vector.

  • tol (float) – Tolerance for angle comparison in degrees.

Returns:

True if line and plane are parallel, False otherwise.

Return type:

bool

pyNanoMatBuilder.utils.geometry.isPlaneOrthogonal2Line(v1, v2, tol=1e-05)

Return True if line direction and plane normal are orthogonal. A line direction vector and a plane are orthogonal if $|angle|$ between the line and the normal vector of the plane is 0° or 180°.

Parameters:
  • v1 (np.ndarray) – Line direction vector.

  • v2 (np.ndarray) – Plane normal vector.

  • tol (float) – Tolerance for angle comparison in degrees.

Returns:

True if line and plane are orthogonal, False otherwise.

Return type:

bool

pyNanoMatBuilder.utils.geometry.areDirectionsOrthogonal(v1, v2, tol=1e-06)

Return True if directions are orthogonal. Lines are orthogonal if the $|angle|$ between their direction vector is 90°

Parameters:
  • v1 (np.ndarray) – First direction vector.

  • v2 (np.ndarray) – Second direction vector.

  • tol (float) – Tolerance for angle comparison in degrees.

Returns:

True if directions are orthogonal, False otherwise.

Return type:

bool

pyNanoMatBuilder.utils.geometry.areDirectionsParallel(v1, v2, tol=1e-06)

Return True if directions are parallel. Lines are parallel if the $|angle|$ between their direction vector is 0° or 180°.

Parameters:
  • v1 (np.ndarray) – First direction vector.

  • v2 (np.ndarray) – Second direction vector.

  • tol (float) – Tolerance for angle comparison in degrees.

Returns:

True if directions are parallel, False otherwise.

Return type:

bool

pyNanoMatBuilder.utils.geometry.shortestPoint2PlaneVectorDistance(plane: ndarray, point: ndarray)

Return the shortest distance, d, from a point X0 to a plane p (projection of X0 on p = P), as well as the PX0 vector.

Parameters:
  • plane (np.ndarray) – [u v w h] definition of the p plane

  • point (np.ndarray) – [x0 y0 z0] coordinates of the X0 point or (N, 3) array of points.

Returns:

the PX0 vector and ||PX0||

Return type:

v,d (tuple)

pyNanoMatBuilder.utils.geometry.Pt2planeSignedDistance(plane, point)

Return the orthogonal distance of a given point X0 to the plane p in a metric space (projection of X0 on p = P), with the sign determined by whether or not X0 is in the interior of p with respect to the center of gravity [0 0 0].

Parameters:
  • plane (np.ndarray) – Array [u, v, w, h] defining the plane.

  • point (np.ndarray) – Array [x0, y0, z0] or (N, 3) array of points.

Returns:

Signed distance(s) to the plane.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.planeAtVertices(coordVertices: ndarray, cog: ndarray)

Returns the equation of the plane defined by vectors between the center of gravity (cog) and each vertex of a polyhedron and that is located at the vertex.

Parameters:
  • coordVertices (np.ndarray) – Coordinates of the vertices (n_vertices, 3).

  • cog (np.ndarray) – Center of gravity of the NP.

Returns:

the (cog-nvertices)x3 coordinates of the plane

Return type:

np.array(plane)

pyNanoMatBuilder.utils.geometry.planeAtPoint(plane: ndarray, P0: ndarray)

Recalculate plane d so the plane passes through P0.

Parameters:
  • plane (np.ndarray) – Array [a, b, c, d].

  • P0 (np.ndarray) – Coordinates [x0, y0, z0].

Returns:

Plane parameters [a, b, c, -(ax0+by0+cz0)].

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.normalizePlane(p)

Normalize plane parameters [a, b, c, d] by the normal norm.

pyNanoMatBuilder.utils.geometry.point2PlaneDistance(point: float64, plane: float64)

Compute the shortest distance between a point and a plane in 3D space.

Parameters:
  • point (np.ndarray) – A 3D point as [x, y, z].

  • plane (np.ndarray) – A plane defined by [A, B, C, D] where Ax + By + Cz + D = 0.

Returns:

The shortest distance from the point to the plane.

Return type:

float

pyNanoMatBuilder.utils.geometry.calculateTruncationPlanesFromVertices(planes, cutFromVertexAt, nAtomsPerEdge, debug=False, noOutput=False, trTd=False)

Calculate truncation planes from vertex planes.

Parameters:
  • planes (np.ndarray) – Array of planes [u, v, w, d].

  • cutFromVertexAt (float) – Fraction of edge length to cut from each vertex.

  • nAtomsPerEdge (int) – Number of atoms per edge.

  • debug (bool) – If True, prints debug information.

  • noOutput (bool) – If True, suppresses output.

Returns:

Truncation planes.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.truncateAboveEachPlane(planes: ndarray, coords, debug: bool = False, delAbove: bool = True, noOutput: bool = False, eps: float = 0.001)

Return atom indices above (or below) each plane.

Parameters:
  • planes (np.ndarray) – Array with plane definitions [u, v, w, d].

  • coords (np.ndarray) – (N, 3) array of coordinates.

  • debug (bool) – If True, prints selected atom indices.

  • delAbove (bool) – If True, deletes atoms above planes + eps; below otherwise.

  • noOutput (bool) – If True, suppresses output.

  • eps (float) – Atom-to-plane signed distance threshold.

Returns:

Unique indices of atoms above/below any input plane.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.truncateAbovePlanes(planes: ndarray, coords: ndarray, allP: bool = False, delAbove: bool = True, debug: bool = False, noOutput: bool = False, eps: float = 0.001, depth_max: float = None)

Return a boolean mask of atoms above/below plane(s).

Parameters:
  • planes (np.ndarray) – Array with plane definitions [u, v, w, d].

  • coords (np.ndarray) – (N, 3) array of coordinates.

  • allP (bool) – If True, deleted atoms must lie simultaneously above ALL individual plane.

  • delAbove (bool) – If True, delete atoms above planes (+eps); below otherwise

  • precaution ((use with)

  • definition) (could return no atoms as a function of their)

  • debug (bool) – If True, prints atoms matching the conditions.

  • noOutput (bool) – If True, suppresses output.

  • eps (float) – Atom-to-plane signed distance threshold.

  • depth_max (float) – Reserved for depth-based filtering.

Returns:

Boolean mask for atoms above/below planes.

Return type:

np.ndarray

pyNanoMatBuilder.utils.geometry.returnPointsThatLieInPlanes(planes: ndarray, coords: ndarray, debug: bool = False, threshold: float = 0.001, noOutput: bool = False)

Finds all points (atoms) that lie within the given planes based on a signed distance criterion.

Parameters:
  • planes (np.ndarray) – A 2D array with plane equations [a, b, c, d].

  • coords (np.ndarray) – A 2D array of atom coordinates [x, y, z].

  • debug (bool, optional) – If True, prints additional debugging information.

  • threshold (float, optional) – Tolerance for distance to consider a point in plane.

  • noOutput (bool, optional) – If True, suppresses output messages.

Returns:

A boolean array where True indicates that the atom lies in one of the planes.

Return type:

AtomsInPlane (np.ndarray)

pyNanoMatBuilder.utils.geometry.coreSurface(self, threshold_CoreSurface: float = 0.001, noOutput=False)

Identify the core and surface atoms of a nanoparticle. This method distinguishes surface atoms from core atoms by calculating the geometric convex hull of the atomic coordinates. It can target either the initial structure (NP) or the relaxed structure (NP_opt).

Parameters:
  • threshold_CoreSurface (float) – The threshold used to identify surface atoms.

  • noOutput (bool) – If True, suppresses output during the analysis.

Returns:

A tuple containing:
  • list: [Hull vertices, Hull simplices, Hull neighbors, Hull equations]

  • surfaceAtoms (numpy.ndarray): A boolean array where True indicates that the atom lies on the surface.

Return type:

tuple

pyNanoMatBuilder.utils.geometry.peel_by_coordination(self, threshold_peeling=6, Rmax=2.9, noOutput=False)

Remove surface atoms with low coordination numbers to simulate truncation or incomplete shell growth.

This method uses a KDTree-based neighbor search (via self.kDTreeCN) to identify and delete atoms that are weakly bonded, such as vertices or edge atoms.

The method updates self.NP in place. If an optimized structure (NPopt) existed, it is used as the coordinate source for the peeling, then deleted. self.is_optimized is reset to False.

Parameters:
  • threshold_peeling (int) – Minimum coordination number required to keep an atom.

  • Rmax (float) – The cutoff distance (in Angstroms) for defining a nearest neighbor.

  • noOutput (bool) – If True, suppresses output messages.

Returns:

The updated nanoparticle (self.NP) after peeling.

Return type:

ase.Atoms

pyNanoMatBuilder.utils.geometry.peel_by_shifted_ellipsoid(self, shift_dist=2.5, noOutput=False)

Truncate the nanoparticle using a shape-adaptive envelope shifted in a random direction.

This method simulates asymmetric growth or partial dissolution by shifting a volume of control (defined by the particle’s own inertia tensor) and removing atoms that fall outside. By projecting coordinates into the Principal Component Analysis (PCA) local frame, the truncation volume perfectly matches the eccentricity of the NP, making it robust for both spherical and cylindrical (nanorod) geometries.

The method updates self.NP in place. If an optimized structure (NP_opt) existed, it is used as the coordinate source, then deleted. self.is_optimized is reset to False.

Parameters:
  • shift_dist (float) – The distance to shift the envelope (in Angstroms). 2.5 A corresponds to approximately one atomic layer.

  • noOutput (bool) – If True, suppresses output messages.

pyNanoMatBuilder.utils.geometry.plot_npr_triangle(self=None, is_optimized: bool = False, save_path: str = None, external_data: dict = None, color_by: str = 'Rg', color: str = 'viridis')

Hybrid Sauer Plot for pyNanoMatBuilder with precise colorbar scaling and bold formatting.

pyNanoMatBuilder.utils.geometry.applyTwist(self, axis: [0, 0, 1], axis_def: str = 'hkl', rate: float = 1.0, profile: str = 'linear', custom_profile=None, pitch: float = None, helix_radius: float = None, chirality='RH', noOutput: bool = False)

Apply a Twist to the atomic positions of a NP along a given crystallographic axis.

Each atomic plane perpendicular to the Twist axis is rotated by an angle that depends on its position along the axis, according to the chosen profile. The ‘helical’ profile additionally translates atoms along the axis proportionally to their rotation angle, producing a helix-like deformation. The ‘helix’ profile bends the entire wire to follow a circular helical path, like a spring. Rotations are computed using a fully vectorized implementation of Rodrigues’ formula — no Python loop over atoms.

Parameters:
  • self – A pyNMBcore instance (Crystal, or any object with self.NP and self.cog).

  • axis (array-like) – Twist axis in crystallographic coordinates [h, k, l] or Cartesian [x, y, z] depending on axis_def.

  • axis_def (str) –

    Defines the coordinate system of the axis argument. Options: ‘hkl’ — axis is given as Miller indices in the crystallographic

    basis; requires a crystal object with a reciprocal metric tensor (Gstar). Use for Crystal NPs built by pyNanoMatBuilder.

    ’cart’ — axis is given as a Cartesian direction [x, y, z]; works

    for any NP, including those loaded from file via from_file().

    Default is ‘hkl’.

  • rate (float) – Twist rate in degrees. Interpretation depends on profile: linear — degrees per Å. sinusoidal — peak amplitude in degrees. gaussian — peak amplitude in degrees. helical — degrees per Å. helix — not used. custom — scaling factor applied to custom_profile(z, L). Default is 1.0.

  • profile (str) – Twist profile along the axis. Options: linear — angle(z) = rate * z. sinusoidal — angle(z) = rate * sin(2π * z / L). gaussian — angle(z) = rate * exp(-z² / 2σ²), σ = L/4. helical — angle(z) = rate * z, plus translation along axis. helix — bends wire to helical path, requires helix_radius and pitch. custom — angle(z) = rate * custom_profile(z, L). Default is 'linear'.

  • custom_profile (callable, optional) –

    A user-defined function f(z, L) -> float where z is the signed distance along the axis in Å, and L is the total length of the NP along the axis in Å. Required when profile=’custom’. Example:

    custom_profile = lambda z, L: np.sin(4 * np.pi * z / L)

  • pitch (float, optional) – Helix pitch in Å per turn (Å/360°). Required when profile=’helical’ or ‘helix’.

  • helix_radius (float, optional) – Radius of the helical path in Å. Required when profile=’helix’.

  • chirality (str) – Handedness of the Twist or helix. 'RH' — Right-Handed (default): counter-clockwise when viewed from the positive axis direction. 'LH' — Left-Handed: mirror image of RH, obtained by flipping the rotation direction or the helix winding direction. Default is 'RH'.

  • noOutput (bool) – If True, suppresses output. Default is False.

Returns:

None. Updates self.NP.positions, self.cog, and calls propPostMake.

Raises:
  • ValueError – If profile is unknown.

  • ValueError – If custom_profile is None when profile=’custom’.

  • ValueError – If custom_profile is not callable.

  • ValueError – If pitch is None when profile=’helical’ or ‘helix’.

  • ValueError – If helix_radius is None when profile=’helix’.

  • ValueError – If axis_def is unknown.

  • ValueError – If axis_def=’hkl’ and Gstar is not available.

Note

The Twist is applied around the center of mass of the NP. The axis is normalized internally. For profiles other than ‘helix’, rotation is performed using a vectorized Rodrigues formula for maximum performance (no Python loop over atoms). Each atomic slice perpendicular to the axis rotates as a rigid body — no intra-slice distortion. Inter-slice bond stretching increases with radial distance from the axis. For profile=’helix’, each slice is displaced and reoriented using the Frenet-Serret frame of the helix — no internal distortion of each slice.

Examples

# Linear Twist along [0, 0, 1], 2°/Å NP.applyTwist(axis=[0, 0, 1], rate=2.0, profile=’linear’)

# Sinusoidal Twist with 45° peak amplitude NP.applyTwist(axis=[0, 0, 1], rate=45.0, profile=’sinusoidal’)

# Wire twisted on itself, 5°/Å, 200 Å/turn NP.applyTwist(axis=[0, 0, 1], rate=5.0, profile=’helical’, pitch=200.0)

# Wire bent to a helical path, radius 50 Å, pitch 100 Å/turn NP.applyTwist(axis=[0, 0, 1], rate=1.0, profile=’helix’,

helix_radius=50.0, pitch=100.0, axis_def=’cart’)

# Custom double-period sinusoidal Twist NP.applyTwist(axis=[0, 0, 1], rate=45.0, profile=’custom’,

custom_profile=lambda z, L: np.sin(4 * np.pi * z / L))

Crystal & Wulff Utilities (crystals.py)

pyNanoMatBuilder.utils.crystals.print_ase_unitcell(system: Atoms)

Function that prints unitcell informations : chemical formula, bravais lattice, n° space group, cell parameters, volume, etc.

Parameters:

class (An instance of the Crystal)

pyNanoMatBuilder.utils.crystals.scaleUnitCell(crystal: Atoms, scaleDmin2: float, noOutput: bool = False)

Scales the unit cell of a given crystal structure to match a target nearest-neighbor distance.

This function expands the unit cell of the input crystal by creating a 2×2×2 supercell, then computes the nearest-neighbor distance and scales the entire structure to match the desired minimum nearest-neighbor distance.

Args: - crystal (Atoms): An ASE Atoms object representing the initial crystal structure. - scaleDmin2 (float): The target nearest-neighbor distance (in Å) after scaling. - noOutput (bool): If True, suppresses output messages.

Returns: - None: The function modifies the input crystal object in place.

Notes:

  • The function first generates a 2×2×2 supercell to ensure a representative environment.

  • It computes the minimum nearest-neighbor distance (Rmin) using kDTreeCN.

  • The structure is then uniformly scaled so that the new nearest-neighbor distance equals scaleDmin2.

  • The ASE set_cell method is used with scale_atoms=True to adjust atomic positions accordingly.

pyNanoMatBuilder.utils.crystals.FindInterAtomicDist(self)

Computes the interatomic distance based on the Bravais lattice (fcc, bcc or hcp only).

Returns:

Interatomic distance

Return type:

float

pyNanoMatBuilder.utils.crystals.convertuvwh2hkld(plane: float64, prthkld: bool = True)

Convert a real plane ux + vy + wz + h = 0 to integer hkl form.

Parameters:
  • plane (np.ndarray) – Array [u, v, w, h].

  • prthkld (bool) – If True, prints the hkl equation.

Returns:

Array [h, k, l, d].

Return type:

np.ndarray

pyNanoMatBuilder.utils.crystals.hklPlaneFitting(coords: float64, printEq: bool = True, printErrors: bool = False)

Context: finding the Miller indices of a plane, if relevant. Consists in a least-square fitting of the equation of a plane hx + ky + lz + d = 0 that passes as close as possible to a set of 3D points.

Parameters:
  • coords (np.ndarray) – array with shape (N,3) that contains the 3 coordinates for each of the N points

  • printErrors (bool) – if True, prints the absolute error between the actual z coordinate of each points

  • printed (and the corresponding z-value calculated from the plane equation. The residue is also)

Returns:

[h k l d], where h, k, and l are as close as possible to integers

Return type:

plane (np.ndarray)

pyNanoMatBuilder.utils.crystals.interPlanarSpacing(plane: ndarray, unitcell: ndarray, CrystalSystem: str = 'CUB')

Calculate the interplanar spacing.

Parameters:
  • plane – numpy array containing the [h k l d] parameters of the plane of equation hx + ky + lz + d = 0.

  • unitcell – numpy array with [a b c alpha beta gamma].

  • CrystalSystem – Name of the crystal system, string among: [‘CUB’, ‘HEX’, ‘TRH’, ‘TET’, ‘ORC’, ‘MCL’, ‘TRI’] = cubic, hexagonal, trigonal-rhombohedral, tetragonal, orthorombic, monoclinic, tricilinic.

Returns:

The interplanar spacing.

Return type:

float

pyNanoMatBuilder.utils.crystals.lattice_cart(Crystal, vectors, Bravais2cart=True, printV=False)

Project vectors between Bravais basis and cartesian coordinate system.

Parameters:
  • Crystal – Crystal object.

  • vectors – Vectors to project from the Bravais basis to the cartesian coordinate system (if Bravais2cart is True) or to project from the cartesian coordinate system to the Bravais basis (if Bravais2cart is False).

  • Bravais2cart (bool) – If True, project from Bravais to cartesian.

  • printV (bool) – If True, prints the resulting vectors.

Returns:

Array of projected vectors.

Return type:

np.ndarray

pyNanoMatBuilder.utils.crystals.G(Crystal)

Compute the metric tensor (G) of a crystal’s unit cell.

The metric tensor is calculated based on the unit cell parameters: the lengths of the unit cell vectors (a, b, c) and the angles (alpha, beta, gamma) between them.

Reference:

https://fr.wikibooks.org/wiki/Cristallographie_g%C3%A9om%C3%A9trique/ Outils_math%C3%A9matiques_pour_l%27%C3%A9tude_du_r%C3%A9seau_cristallin

Parameters:

Crystal – Crystal object.

Returns:

The 3x3 metric tensor (G) of the unit cell.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.crystals.Gstar(Crystal)

Compute the inverse of the metric tensor (G*) for a crystal’s unit cell.

Parameters:

Crystal – Crystal object.

Returns:

The 3x3 inverse metric tensor (G*) of the unit cell.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.crystals.spacegroup_to_bravais(sg_number: int, hm_symbol: str = '') tuple[str, str]

Return the crystal system acronyms compatible with interPlanarSpacing() from the international space group number and Hermann-Mauguin symbol.

Parameters:
  • sg_number (int) – International space group number (1-230).

  • hm_symbol (str) – Hermann-Mauguin symbol (e.g. ‘F m -3 m’, ‘R -3 m’, ‘P 63/m m c’). Only the first character is used. Default is ‘’.

Returns:

  • crystal_system (str): Crystal system acronym compatible with interPlanarSpacing(), among: ‘TRI’, ‘MCL’, ‘ORC’, ‘TET’, ‘TRH’, ‘HEX’, ‘CUB’

  • bravais_lattice (str): Extended Bravais lattice acronym, among: ‘TRI’ : triclinic ‘MCL’ : simple monoclinic ‘MCLC’ : base-centered monoclinic ‘ORC’ : simple orthorhombic ‘ORCF’ : face-centered orthorhombic ‘ORCI’ : body-centered orthorhombic ‘ORCC’ : base-centered orthorhombic ‘TET’ : simple tetragonal ‘BCT’ : body-centered tetragonal ‘TRH’ : trigonal rhombohedral ‘HEX’ : hexagonal / trigonal hexagonal axes ‘CUB’ : simple cubic ‘FCC’ : face-centered cubic ‘BCC’ : body-centered cubic

Return type:

tuple[str, str]

Raises:

ValueError – If sg_number is not in range 1-230.

Examples

>>> spacegroup_to_bravais(225, 'F m -3 m')
('CUB', 'FCC')
>>> spacegroup_to_bravais(229, 'I m -3 m')
('CUB', 'BCC')
>>> spacegroup_to_bravais(194, 'P 63/m m c')
('HEX', 'HEX')
>>> spacegroup_to_bravais(146, 'R -3 m')
('TRH', 'TRH')
>>> spacegroup_to_bravais(12, 'C 1 2/m 1')
('MCL', 'MCLC')
>>> spacegroup_to_bravais(69, 'F m m m')
('ORC', 'ORCF')
pyNanoMatBuilder.utils.crystals.crystallographic_angle(self, v1, v2, type1: str = 'direction', type2: str = 'direction', noOutput: bool = True)

Compute the angle between two crystallographic objects (directions or planes) in any crystal system.

Parameters:
  • self – A pyNMBcore instance with Gstar and G metric tensors.

  • v1 (array-like) – First vector [h, k, l] or [u, v, w].

  • v2 (array-like) – Second vector [h, k, l] or [u, v, w].

  • type1 (str) – Nature of v1: ‘direction’ [uvw] or ‘plane’ (hkl). Default is ‘direction’.

  • type2 (str) – Nature of v2: ‘direction’ [uvw] or ‘plane’ (hkl). Default is ‘direction’.

  • noOutput (bool) – If True, suppresses output. Default is True.

Returns:

Angle in degrees between the two objects.

Return type:

float

Raises:

ValueError – If type1 or type2 is not ‘direction’ or ‘plane’.

Examples

# Angle between two directions in hcp NP.crystallographic_angle([0,0,1], [1,0,0],

type1=’direction’, type2=’direction’)

# Angle between two planes in fcc NP.crystallographic_angle([1,1,1], [1,0,0],

type1=’plane’, type2=’plane’)

# Angle between direction [110] and plane (115) in fcc NP.crystallographic_angle([1,1,0], [1,1,5],

type1=’direction’, type2=’plane’)

Note

All vectors are converted to Cartesian coordinates via lattice_cart before angle computation, ensuring correctness for all crystal systems including non-orthogonal lattices (hexagonal, trigonal, monoclinic, triclinic).

  • Direction-direction angle [u1v1w1] vs [u2v2w2]: both converted to Cartesian, angle computed directly.

  • Plane-plane angle (h1k1l1) vs (h2k2l2): plane normals computed via G* then converted to Cartesian.

  • Direction-plane angle [uvw] vs (hkl): 90° minus the angle between the direction and the plane normal.

pyNanoMatBuilder.utils.crystals.generateSlab(self, hkl, size_a: float = 2.0, size_b: float = 2.0, min_thickness: float = 5.0, n_layers: int = None, vacuum: float = 10.0, backend: str = 'ase', primitive: bool = False, noOutput: bool = None)

Generate a crystallographic slab from Miller indices (hkl).

Parameters:
  • self – A Crystal instance with self.cif and self.crystal defined.

  • hkl (array-like) – Miller indices [h, k, l] of the surface plane.

  • size_a (float) – Target slab dimension along a in nm. Default is 2.0.

  • size_b (float) – Target slab dimension along b in nm. Default is 2.0.

  • min_thickness (float) – Minimum slab thickness in Å. Default is 5.0. For backend=’ase’, converted to an estimated number of layers. For backend=’pymatgen’, passed directly as min_slab_size.

  • n_layers (int) – If provided, overrides min_thickness and directly specifies the number of layers passed to the backend. For ASE: number of repetitions of the surface unit cell (not necessarily equal to atomic layers). For pymatgen: number of unit planes (in_unit_planes=True). Default is None (use min_thickness instead).

  • vacuum (float) – Vacuum thickness in Å on each side. Default is 10.0.

  • backend (str) – Slab generation backend: ‘ase’ or ‘pymatgen’. ‘pymatgen’ gives better control over slab thickness via min_thickness in Å. Default is ‘ase’.

  • primitive (bool) – pymatgen backend only. If True, uses the primitive surface cell (smaller, with diagonal <110> vectors for (100) fcc). If False, uses the conventional surface cell aligned with principal crystallographic axes, which is consistent with ASE orientation. Default is False.

  • noOutput (bool) – If True, suppresses output. Default is self.noOutput.

Returns:

A shallow copy of the parent Crystal instance with

self.NP replaced by the generated slab.

Return type:

pyNMBcore

pyNanoMatBuilder.utils.crystals.direction_to_plane(self, uvw, cartesian=False)

Return the Miller indices (hkl) of the plane perpendicular to the crystallographic direction [uvw]. In a cubic system: (hkl) = (uvw). In general: uses the metric tensor G to convert.

Parameters:
  • uvw (array-like) – Direction [u, v, w] in crystallographic coordinates.

  • cartesian (bool) – If True, returns the plane normal as a Cartesian vector instead of Miller indices. Default is False.

Returns:

Miller indices [h, k, l] as smallest integers,

or Cartesian normal vector if cartesian=True.

Return type:

np.ndarray

pyNanoMatBuilder.utils.crystals.plane_to_direction(self, hkl, cartesian=False)

Return the crystallographic direction [uvw] perpendicular to the plane (hkl). In a cubic system: [uvw] = [hkl]. In general: uses the reciprocal metric tensor G* to convert.

Parameters:
  • hkl (array-like) – Miller indices [h, k, l].

  • cartesian (bool) – If True, returns the direction as a Cartesian vector instead of crystallographic indices. Default is False.

Returns:

Direction [u, v, w] as smallest integers in

crystallographic coordinates, or Cartesian vector if cartesian=True.

Return type:

np.ndarray

I/O (io.py)

pyNanoMatBuilder.utils.io.returnUnitcellData(system)

Function that calculates various unit cell properties from the system.cif object and assigns them to attributes within the system instance.

Parameters:

data. (An instance of the Crystal class containing CIF file)

pyNanoMatBuilder.utils.io.listCifsOfTheDatabase()

Display all CIF filenames in the database.

pyNanoMatBuilder.utils.io.get_crystal_type(self)

Find the Bravais lattice based on the space group number.

Returns:

Bravais lattice

Return type:

str

pyNanoMatBuilder.utils.io.extract_cif_info(self, cif_file)

Extract useful information from a CIF file.

Parameters:

cif_file – CIF file.

Returns:

A dictionary containing extracted CIF information:
  • ’cif_path’ (Path): Absolute path to the CIF file.

  • ’crystal_type’ (str): The crystal type.

  • ’Unitcell_param’ (list): Unit cell parameters [a, b, c, α, β, γ].

  • ’ucBL’ (str): Bravais lattice type.

Return type:

dict

pyNanoMatBuilder.utils.io.load_cif(self, cif_file, noOutput)

Loads a CIF file and extracts its information if it has not been loaded before. :param cif_file: a CIF file. :param noOutput: If False, prints the CIF file path. :type noOutput: bool

Returns:

Extracted CIF information (from extract_cif_info).

Return type:

dict

Notes: - CIF files are assumed to be stored in the “cif_database” directory. - If the file has already been loaded, its information is retrieved from self.loaded_cifs.

pyNanoMatBuilder.utils.io.ciflist(dbFolder='resources/cif_database')

Function that prints the CIF files in the built-in dataset. :param dbFolder: The database folder name (default is resources/cif_database).

pyNanoMatBuilder.utils.io.write(filename: str, atoms, wa='w', **kwargs)

Unified write function for pyNanoMatBuilder.

This function serves as a central hub for exporting data. It handles directory creation automatically and routes the data to the appropriate writer based on the file extension.

Parameters:
  • filename (str) – Path to the output file (e.g., ‘coords/np.xyz’).

  • atoms (ase.Atoms or str) – The atomic structure to save, or a string containing script content for .script/.spt files.

  • wa (str, optional) – Write mode. ‘w’ for overwrite (default) or ‘a’ for append (useful for multi-frame trajectories).

  • **kwargs – Additional arguments passed to the underlying ASE write function (e.g., ‘format’).

Note

  • Automatically creates parent directories if they do not exist.

  • Uses internal ‘writexyz’ for .xyz files to preserve custom headers.

  • Uses ASE for crystallography formats (.cif, .res, .pdb, etc.).

  • Handles raw text writing for Jmol scripts (.script, .spt).

pyNanoMatBuilder.utils.io.writexyz(filename: str, atoms: Atoms, wa: str = 'w')

Simple xyz writing, with atomic symbols/x/y/z and no other information. Automatically creates the parent directories if they do not exist. :param filename: Output filename. :type filename: str :param atoms: ASE Atoms object. :type atoms: Atoms :param wa: Write mode (‘w’ or ‘a’). :type wa: str

pyNanoMatBuilder.utils.io.create_data_csv(path_of_files, path_of_csvfiles, noOutput)

Extract dictionaries from XYZ/CSV files and create new CSV files.

Parameters:
  • path_of_files – Path of the directory containing the files.

  • path_of_csvfiles – Path of the directory where the CSV file will be created.

  • noOutput – If True, suppresses print statements.

Returns:

None

pyNanoMatBuilder.utils.io.imageNameWithPathway(imgName)

Construct the full file path for an image.

Constructs the full file path for an image by joining the base directory with the image name.

Parameters:

imgName (str) – The name of the image file.

Returns:

The full file path to the image file.

Return type:

str

pyNanoMatBuilder.utils.io.plotImageInPropFunction(imageFile, figsize=(2, 10), rot=0)

Plot an image using matplotlib with optional rotation and no axes.

Parameters:
  • imageFile (str) – The path to the image file to be displayed.

  • figsize (tuple) – Figure size (width, height) in inches.

  • rot (float) – Rotation angle in degrees (counter-clockwise).

pyNanoMatBuilder.utils.io.createDir(path2, forceDel=False)

Creates a directory at the specified path.

If the directory already exists, it will either be left unchanged or deleted and recreated based on the ‘forceDel’ argument.

Parameters:
  • path2 (str) – The path where the directory should be created.

  • forceDel (bool, optional) – If set to True, will delete the existing directory and recreate it. Default is False.

Returns:

None

Energy (energy.py)

pyNanoMatBuilder.utils.energy.full_diagnosticsEMT(atoms, verbose=True)

Run basic diagnostics on an ASE Atoms object for EMT calculations.

Parameters:
  • atoms – ASE Atoms object to diagnose.

  • verbose (bool) – If True, prints diagnostic details.

Returns:

True if no obvious fatal problems are found, else False.

Return type:

bool

pyNanoMatBuilder.utils.energy.optimizeEMT(model: Atoms, saveCoords=True, pathway='./coords/model', fthreshold=0.1)

Optimize the geometry of an atomic system using EMT and Quasi-Newton.

Parameters:
  • model (ase.Atoms) – Atomic system to optimize.

  • saveCoords (bool, optional) – If True, saves the optimized coordinates.

  • pathway (str, optional) – Path to save the trajectory and final structure.

  • fthreshold (float, optional) – Convergence threshold for forces (in eV/Å).

Returns:

Optimized atomic model.

Return type:

ase.Atoms

pyNanoMatBuilder.utils.energy.optimize(self, calculator='EMT', optimizer='QN', fthreshold=0.1)

Optimize the geometry of an atomic system using various energy calculators and geometry optimization algorithms.

Parameters:
  • model (ase.Atoms) – Atomic system to optimize.

  • saveCoords (bool, optional) – If True, saves the optimized coordinates.

  • pathway (str, optional) – Path to save the trajectory and final structure.

  • fthreshold (float, optional) – Convergence threshold for forces (in eV/Å).

Creates:

self.NP_opt (ase.Atoms): Optimized atomic model.

The following properties are also created, by calling propPostMake()

self.cog_opt self.vertices_opt self.simplices_opt self.neighbors_opt self.equations_opt jMolCS_opt

Properties (prop.py)

pyNanoMatBuilder.utils.prop.calculateCN(coords, Rmax)

Calculate the coordination number (CN) for each atom.

The coordination number is determined by counting neighbors within a spherical cutoff distance defined by Rmax.

Parameters:
  • coords (numpy.ndarray) – An (N, 3) array containing the Cartesian coordinates for each of the N points.

  • r_max (float) – The threshold distance (cutoff) used to define a coordination bond.

Returns:

An array of length N containing the calculated

coordination number for each atom.

Return type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.delAtomsWithCN(coords: ndarray, Rmax: float64, targetCN: int = 12)

Return the coordination number of each atom.

CN is calculated after threshold Rmax.

Parameters:
  • coords – numpy array with shape (N,3) containing 3 coordinates for each of N points.

  • Rmax – threshold to calculate CN.

Returns:

Array containing CN for each atom.

Return type:

np.ndarray

pyNanoMatBuilder.utils.prop.findNeighbours(coords, Rmax)

Find all atoms j within cutoff distance Rmax from atom i.

For all atoms i, returns the list of all atoms j within an arbitrarily determined cutoff distance Rmax from atom i.

Parameters:
  • coords – numpy array with the N-atoms cartesian coordinates.

  • Rmax – cutoff distance.

Returns:

List of lists (len(list[i]) = number of nearest neighbours of atom i).

Return type:

list

pyNanoMatBuilder.utils.prop.printNeighbours(nn)

Print the list of nearest neighbours of each atom.

Parameters:

nn – Nearest neighbours given as a list of lists.

pyNanoMatBuilder.utils.prop.magicNumbers(cluster, i)

Calculate magic numbers for nanocluster stable structures.

Certain collections of atoms are more preferred due to energy minimization and exhibiting stable structures and providing unique properties to the materials. These collections of atoms providing stable structures to the materials are called MAGIC NUMBERS.

This function uses specific formulas based on the type of nanocluster (e.g., ‘regfccOh’, ‘regIco’, ‘fccCube’, etc.) to calculate a magic number based on the index i.

Parameters:
  • cluster (str) – The type of nanocluster for which the magic number is calculated. It can be one of the following values: ‘regfccOh’, ‘regIco’, ‘regfccTd’, ‘regDD’, ‘fccCube’, ‘bccCube’, ‘fccCubo’, ‘fccTrOh’, ‘fccTrCube’, ‘bccrDD’, ‘fccdrDD’, ‘pbpy’.

  • i (int) – The index of the nanocluster size. It must be a positive integer greater than zero.

Returns:

The calculated magic number for the specified nanocluster type

and index i.

Return type:

float

pyNanoMatBuilder.utils.prop.rdf(NP: Atoms, dr: float = 0.05, sigma: float = 2, ncores: int = 1, noOutput: bool = True)

rdf - g(r) - calculator for non-PBC systems.

Parameters:
  • NP (Atoms) – ase Atoms object

  • dr (float) – determines the spacing between successive radii over which g(r) is computed. Default: 0.05

  • sigma (float) – standard deviation for Gaussian kernel. Default: 2

  • ncores (int) – number of jobs to schedule for parallel processing (only used by query_ball_point() of scipy.spatial.KDTree). Default: 1

  • noOutput (bool) – do not print anything. Default: True

Returns:

  • r and g(r)

Wanna know more? Read https://doi.org/10.1021/acs.chemrev.1c00237

pyNanoMatBuilder.utils.prop.compute_moi(model: Atoms, noOutput: bool = False)

Get the moments of inertia along the principal axes.

Notes

Units of the moments of inertia are amu.angstrom**2. Periodic boundary conditions are ignored.

pyNanoMatBuilder.utils.prop.get_moments_of_inertia_for_size(self, vectors=False)

Get the moments of inertia along the principal axes with mass normalization.

Parameters:

vectors (bool, optional) – If True, returns both eigenvalues and eigenvectors. If False, returns only eigenvalues. Defaults to False.

Returns:

Principal moments of inertia (3 values). np.ndarray: Principal axes (3x3 matrix) if vectors is True.

Return type:

np.ndarray

Notes

Periodic boundary conditions are ignored. Units of the moments of inertia are angstrom**2.

pyNanoMatBuilder.utils.prop.moi_size(model: Atoms, noOutput: bool = False)

Get the moments of inertia along the principal axes with mass normalization.

Notes

Units of the moments of inertia are angstrom**2.

pyNanoMatBuilder.utils.prop.calculate_rg(model: Atoms, mass_weighted=True, noOutput: bool = False)

Calculates the radius of gyration for an ASE Atoms object.

Parameters:
  • atoms (ase.Atoms) – The system to analyze.

  • mass_weighted (bool) – If True, weights by atomic mass. If False, calculates geometric Rg.

  • noOutput (bool) – If False, prints a formatted summary.

Returns:

The radius of gyration in nm.

Return type:

float

pyNanoMatBuilder.utils.prop.calculate_npr(moi, noOutput: bool = False)

Calculates Normalized Principal Moments of Inertia (NPR).

Returns:

[npr1, npr2] where npr1 = I1/I3 and npr2 = I2/I3.

Returns (1.0, 1.0) for single atoms to avoid division by zero.

Return type:

list

pyNanoMatBuilder.utils.prop.Inscribed_circumscribed_spheres(self, noOutput)

Calculates the diameters of the inscribed and circumscribed spheres for the nanoparticle (NP) based on its positions and the plane equations.

The circumscribed sphere is the smallest sphere that completely encloses the NP, while the inscribed sphere is the largest sphere that fits within the NP.

Parameters:

noOutput (bool, optional) – If set to True, suppresses output during the analysis. Default is False.

Returns:

The function updates the object’s attributes with the calculated

radius of the spheres, in Angströms.

Return type:

None

Notes

The circumscribed sphere radius is calculated as the maximum distance from the center of gravity (COG) to the NP positions, and the inscribed sphere radius is calculated as the minimum distance from the NP positions to the planes (based on Hull equations)

pyNanoMatBuilder.utils.prop.get_ellipsoid_analysis(self, noOutput=False)

Perform a Principal Component Analysis (PCA) on the outer envelope to calculate the best-fitting circumscribed ellipsoid.

This method identifies the principal axes of the nanoparticle’s surface by analyzing the covariance matrix of the Convex Hull vertices. The resulting ellipsoid is scaled such that its major semi-axis matches the maximum radial distance found in the structure, ensuring a perfect fit for circumscribed diameter measurements (e.g., 1.63 nm for a 3-shell icosahedron).

The analysis automatically selects between ‘initial structure’ and ‘optimized structure’ based on the current state of the object.

Parameters:

noOutput (bool) – If True, suppresses printed summaries and Jmol command generation. Defaults to False.

Returns:

A dictionary containing the following physical properties:
  • ”status”: String indicating which envelope was analyzed.

  • ”D1”, “D2”, “D3”: Major, intermediate, and minor diameters (Å).

  • ”volume”: Volume of the ellipsoid (ų).

  • ”surface”: Approximate surface area (Ų) using Knud Thomsen’s formula.

  • ”asphericity”: Ratio of D1/D3 (1.0 for a perfect sphere).

Return type:

dict

Raises:

ValueError – If fewer than 4 Hull vertices are found, indicating that coreSurface() has not been run or the NP is invalid.

Notes

  • Scaling Logic: The semi-axes are derived from the square root of the eigenvalues of the covariance matrix. The scale factor is defined as: scale = max_radius / sqrt(max_eigenvalue).

  • Surface Area: Calculated using an approximation with p=1.6075, limiting the maximum relative error to 1.061%.

  • Visualization: Generates a Jmol-ready command using the ‘AXES’ and ‘CENTER’ keywords for precise orientation.

pyNanoMatBuilder.utils.prop.external_facets_info(self, mode='auto', noOutput=False)

Compute and display geometric properties of each facet of the NP, based on either the Wulff construction planes or the convex hull planes.

Two labeling modes depending on the selected planes: - Wulff mode (trPlanes_Wulff): facets are labeled by Miller indices from

self.surfacesWulff. Relative surface energies are computed from the Wulff distances via the Wulff theorem (e_i ∝ d_i).

  • Hull mode (trPlanes or trPlanes_opt): facets are labeled by their Miller indices (if convertible) or Cartesian normal direction. Relative energies are computed from distances.

In all modes, facet areas are computed from the reduced convex hull facets (same as used in defCrystalShapeForJMol), and each hull facet is matched to its corresponding plane by maximizing the dot product between the facet normal and the plane normals. Facets absent from the reduced hull are reported as warnings.

Parameters:
  • mode (str) –

    Which truncation planes to use. Options: - ‘auto’ : automatically selects trPlanes_Wulff if

    available, then trPlanes_opt, then trPlanes.

    • ’Wulff’use trPlanes_Wulff with Miller index labeling

      and relative energy computation.

    • ’Slices’ : used trPlanes_Slices

    • ’crystal’ : use trPlanes (initial structure).

    • ’crystal_opt’ : use trPlanes_opt (optimized structure).

    Default is ‘auto’.

  • noOutput (bool) – If True, suppresses all printed output. Default is False.

Returns:

  • distances (np.ndarray): orthogonal distance from origin to each plane in Å.

  • e_relative (np.ndarray): relative surface energies normalized to 1 for the most stable face.

  • facet_areas_per_plane (list of float): area in Ų of each facet. 0.0 if absent from the reduced hull.

Returns None if no truncation planes are available.

Return type:

tuple or None

pyNanoMatBuilder.utils.prop.propPostMake(self, skipChiralityCalculation, skipSymmetryAnalyzis, thresholdCoreSurface, noOutput, is_optimized=False)

Compute and store various post-construction properties of the nanoparticle.

This function calculates moments of inertia (MOI), determines the nanoparticle shape, analyzes symmetry (if required), and identifies core and surface atoms.

Parameters:
  • skipChiralityCalculation (bool) – If True, skips the calculation of the opd index

  • skipSymmetryAnalyzis (bool) – If True, skips symmetry analysis.

  • thresholdCoreSurface (float) – Threshold to distinguish core and surface atoms.

  • noOutput (bool) – If True, suppresses output messages.

pyNanoMatBuilder.utils.prop.moi

Moment of inertia tensor.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.moisize

Normalized moments of inertia.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.vertices

Geometric vertices of the nanoparticle.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.simplices

Simplices defining the convex hull.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.neighbors

Neighboring relations between facets.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.equations

Plane equations for the hull faces.

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.NPcs

Copy of the nanoparticle with surface atoms visually marked.

Type:

ase.Atoms

pyNanoMatBuilder.utils.prop.NP

Original nanoparticle object.

Type:

ase.Atoms

pyNanoMatBuilder.utils.prop.sasview_dims

Dimensions for SasView, calculated only if the sasview_dims() method exists.

Type:

tuple, optional

pyNanoMatBuilder.utils.prop.NPR

normalized ratios of principal moments of inertia $NPR_{1}=I_{1}/I_{3}$ and $NPR_{2}=I_{2}/I_{3}$

Type:

numpy.ndarray

pyNanoMatBuilder.utils.prop.Rg

Radius of Gyration, in nm

Type:

float

pyNanoMatBuilder.utils.prop.compute_opd_index(NP: Atoms, cutoff=6.0, noOutput=False)

High-performance Scaled Osipov–Pickup–Dunmur chirality index computation. Article: 10.1080/00268979500100831 Uses KDTree for neighbor searching and Numba for parallelized math.

Parameters:
  • NP (ase.Atoms) – ase object.

  • cutoff (float) – Radius for neighbor search (in Angstroms).

Returns:

The scaled chirality index G0s.

Return type:

float

External programs (external_pgm.py)

pyNanoMatBuilder.utils.external_pgm.check_jmol()
pyNanoMatBuilder.utils.external_pgm.saveCoords_DrawJmol(asemol, prefix, scriptJ='', boundaries=False, noOutput=True)

Save coordinates and generate a Jmol visualization.

Parameters:
  • asemol – ASE Atoms object to visualize.

  • prefix (str) – Filename prefix for output files.

  • scriptJ (str) – Additional Jmol script commands.

  • boundaries (bool) – If True, draws boundaries without facets script.

  • noOutput (bool) – If True, suppresses command output.

pyNanoMatBuilder.utils.external_pgm.defCrystalShapeForJMol(self, noOutput: bool = True)

Generate a Jmol command to visualize the crystal shape based on the facets of the NP.

Parameters:

noOutput (bool) – If True, suppresses the output of the command.

Returns:

The Jmol command string for visualizing the crystal shape.

Return type:

str

pyNanoMatBuilder.utils.external_pgm.saveCN4JMol(Crystal: Atoms, save2: str = 'CN.dat', Rmax: float = 3.0, noOutput: bool = False)

Calculates the coordination number (CN) for a given crystal and generates a Jmol command for visualization.

Parameters:
  • Crystal (Atoms) – The crystal structure object.

  • save2 (str, optional) – The filename to save the coordination numbers. Defaults to ‘CN.dat’.

  • Rmax (float, optional) – The maximum distance for neighbors when calculating CN. Defaults to 3.0.

  • noOutput (bool, optional) – If set to True, suppresses the output. Defaults to False.

Returns:

None

pyNanoMatBuilder.utils.external_pgm.DrawJmol(mol, prefix, scriptJ='', noOutput=True)

Generate a Jmol visualization from an existing XYZ file.

pyNanoMatBuilder.utils.external_pgm.defHelixShapeForJMol(self, n_rings=50, n_sides=12, noOutput=True)

Generate a Jmol command to visualize the helical envelope as a triangulated tube.

The tube is built by connecting successive rings of n_sides points each, placed perpendicular to the helix tangent at each sample point. Each pair of adjacent rings generates 2*n_sides triangles. The tube is automatically centered on the NP center of mass.

Parameters:
  • n_rings (int) – Number of rings along the helix (default: 50).

  • n_sides (int) – Number of vertices per ring (default: 12).

  • noOutput (bool) – If True, suppresses output. Default is True.

Returns:

Jmol command string for the helical tube.

Return type:

str

pyNanoMatBuilder.utils.external_pgm.defSlabShapeForJMol(self, hkl, offset: float = 1.5, noOutput: bool = True)

Generate a Jmol command to visualize the slab surface plane as a translucent polygon, positioned just above the topmost atomic layer.

The polygon is defined by the four corners of the slab surface cell (spanned by cell vectors a and b), centered on the slab center of mass, and placed at z_max + offset to aflush with the top atomic layer. Edges are drawn as thin lines and the plane is labeled with its Miller indices.

Parameters:
  • hkl (array-like) – Miller indices [h, k, l] of the surface plane, used for labeling only.

  • offset (float) – Vertical offset in Å above the topmost atomic layer at which the surface polygon is placed. Should be approximately half the atomic radius of the surface element (default: 1.5 Å, suitable for Au, Ag, Pt).

  • noOutput (bool) – If True, suppresses printing of the Jmol command. Default is True.

Returns:

Jmol command string defining the surface polygon, its edges,

and its Miller index label.

Return type:

str

Note

This function is intended for use on objects returned by generateSlab(). The polygon approximates the surface as a flat quadrilateral — it is exact only if the slab cell vectors a and b lie in the surface plane, which is the case for slabs generated by ASE or pymatgen surface builders.

Example

slab = AuNP.generateSlab([1, 1, 5], size_a=2.0, size_b=2.0,

min_thickness=10.0, backend=’ase’)

script = slab.defSlabShapeForJMol([1, 1, 5], offset=1.7) pyNMBu.write(‘coords/Au_115.script’, script)

Visualization (visualID.py)

pyNanoMatBuilder.visualID.apply_css_style()

Explicitly reads and applies the visualID CSS stylesheet from the package resources.

pyNanoMatBuilder.visualID.display_md(text)
pyNanoMatBuilder.visualID.hdelay(sec)
pyNanoMatBuilder.visualID.hdelay_ms(delay)
pyNanoMatBuilder.visualID.init()

Initializes the notebook environment: applies CSS, displays the banner, and shows hostname/time. Also reports the parallel computing status

pyNanoMatBuilder.visualID.end()

Terminates the notebook session: displays duration, end time, and the termination logo from package resources.