Structures Module¶
Tools to generate, manipulate, and analyze nanoscale and bulk materials.
Capabilities:
0D (clusters, nanoparticles), 1D (nanowires, nanotubes), 2D (nanosheets, thin films), and bulk crystals
Automated builders for nanoclusters, nanotubes, and supercells
Geometric operations: rotation, translation, scaling, merging, slicing, symmetry analysis
Supports formats: .cif, .xyz, .pdb, .vasp, .json
Integration with ASE and Pymatgen via built-in converters
Structures subpackage for pygamlab: Contains atomic primitives, nanostructure architectures, I/O utilities, and visualization.
- class PyGamLab.structures.AdvancedAlloys(elements, fractions, crystal_structures=None, lattice_constants=None, supercell_size=(3, 3, 3), seed=None, verbose=True, metadata=None)[source]
Bases:
objectGenerator for multi-element random alloys with customizable crystal structures and lattice constants.
The AdvancedAlloys class allows the creation of randomized substitutional alloys from multiple metallic or intermetallic elements, with user-defined stoichiometric fractions, crystal types (e.g., fcc, bcc, hcp), and lattice parameters. It can handle both simple and mixed lattice systems, automatically constructing ASE-compatible supercells and mapping them into GAM-compatible GAM_Atom objects.
The class provides full control over alloy composition, randomization, and reproducibility via random seeds. It also supports both isotropic and anisotropic (hexagonal) lattice constants and offers structure export and transformation operations (translation, rotation, etc.).
- Parameters:
elements (list of str) – Chemical symbols of alloy components (e.g.,
['Cu', 'Ni', 'Co']).fractions (list of float) – Fractional composition of each element. Must sum to 1.0.
crystal_structures (list of str, optional) – Crystal structure type for each element (e.g.,
['fcc', 'fcc', 'hcp']). If omitted, defaults are taken from the internal lattice database.lattice_constants (list of float or list of dict, optional) –
Lattice constants for each element. Each entry can be:
A float (for cubic lattices), e.g.
3.615A dict with keys like
{'a': 2.95, 'c': 4.68}for hexagonal lattices
If omitted, values are retrieved from the internal lattice database.
supercell_size (tuple of int, default=(3, 3, 3)) – Supercell replication factors along the (x, y, z) directions.
seed (int, optional) – Random seed for reproducible alloy configurations.
verbose (bool, default=True) – If True, prints diagnostic information during structure generation.
metadata (dict, optional) – Additional metadata for traceability or simulation setup.
- atoms
List of atomic objects in GAM-compatible format.
- Type:
list[GAM_Atom]
- ASE_atoms
The underlying ASE Atoms object containing the generated structure.
- Type:
ase.Atoms
- bonds
List of bonds (optional; currently not populated by default).
- Type:
list[GAM_Bond]
- elements
Element symbols defining the alloy system.
- Type:
list[str]
- fractions
Fractional composition of elements.
- Type:
list[float]
- crystal_structures
Crystal structure assigned to each element.
- Type:
list[str]
- lattice_constants
Lattice constants for each component.
- Type:
list[float or dict]
- supercell_size
Supercell replication dimensions.
- Type:
tuple[int, int, int]
- meta
Dictionary storing all structure metadata.
- Type:
dict
- origin
Origin coordinates for translation and rotation.
- Type:
tuple[float, float]
- rotation
Rotation angle of the system (degrees).
- Type:
float
- _set_defaults()[source]
Set default crystal structures and lattice constants based on a predefined database.
- _build_advanced_structure() ase.Atoms[source]
Build the random alloy supercell using ASE’s bulk crystal generator.
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by a displacement vector.
- rotate(angle_deg, about_center=True)[source]
Rotate the alloy structure around the z-axis.
- copy()[source]
Return a deep copy of the structure.
- get_atoms() list[GAM_Atom][source]
Retrieve a deep copy of all atoms in GAM format.
- get_positions() list[tuple[float, float, float]][source]
Return Cartesian coordinates of all atoms.
- get_elements() list[str][source]
Return element symbols of all atoms.
- to_xyz(path: str)[source]
Save the generated structure to an XYZ file.
- to_ase() ase.Atoms[source]
Export the structure as an ASE Atoms object.
Notes
If no crystal structure or lattice constant is provided for an element, the class retrieves default values from an internal lattice database (DEFAULT_LATTICE_DB).
All elements are randomly assigned to atomic sites in the supercell according to the specified composition fractions.
Hexagonal lattices must define both ‘a’ and ‘c’ lattice constants.
The randomization is deterministic if a seed is provided.
The final composition may vary slightly due to integer rounding of atom counts in the finite supercell.
Examples
>>> from pygamlab import AdvancedAlloys
>>> # 1. Create a ternary fcc random alloy >>> alloy = AdvancedAlloys( ... elements=['Cu', 'Ni', 'Co'], ... fractions=[0.4, 0.3, 0.3], ... crystal_structures=['fcc', 'fcc', 'fcc'], ... lattice_constants=[3.61, 3.52, 3.55], ... supercell_size=(4, 4, 4), ... seed=42 ... ) >>> alloy.to_xyz("CuNiCo.xyz")
>>> # 2. Create an hcp binary alloy with anisotropic lattice constants >>> alloy = AdvancedAlloys( ... elements=['Ti', 'Al'], ... fractions=[0.7, 0.3], ... crystal_structures=['hcp', 'hcp'], ... lattice_constants=[{'a': 2.95, 'c': 4.68}, {'a': 2.86, 'c': 4.57}], ... supercell_size=(3, 3, 2) ... ) >>> ase_atoms = alloy.to_ase()
>>> # 3. Randomized quaternary alloy (defaults to fcc) >>> alloy = AdvancedAlloys(['Fe', 'Ni', 'Cr', 'Mn'], [0.25, 0.25, 0.25, 0.25]) >>> alloy.to_xyz("FeNiCrMn.xyz") >>> print(len(alloy.atoms), "atoms generated.")
- copy()[source]
Create a deep copy of the structure.
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Return type:
Optional[Atoms]- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.GAM_Atom(id, element='C', x=0.0, y=0.0, z=0.0, metadata=None, charge=0.0, electronic_state=ElectronicState.GROUND_STATE)[source]
Bases:
objectAdvanced atom class for computational chemistry and molecular modeling applications.
The GAM_Atom class represents individual atoms within molecular systems and provides comprehensive functionality for scientific calculations including molecular dynamics simulations, quantum chemistry computations, and structural analysis. It maintains backward compatibility with simple atomic representations while offering advanced features for sophisticated scientific workflows.
- id
Unique identifier for the atom within a molecular system.
- Type:
int
- element
Chemical element symbol (e.g., ‘C’, ‘H’, ‘O’, ‘N’).
- Type:
str
- x
X-coordinate position in Angstroms.
- Type:
float
- y
Y-coordinate position in Angstroms.
- Type:
float
- z
Z-coordinate position in Angstroms.
- Type:
float
- charge
Formal charge of the atom in elementary charge units.
- Type:
float
- electronic_state
Electronic state enumeration (ground, excited, ionized).
- Type:
ElectronicState
- atomic_number
Atomic number from periodic table.
- Type:
int
- atomic_mass
Atomic mass in atomic mass units (AMU).
- Type:
float
- electron_configuration
Electron configuration string.
- Type:
str
- covalent_radius
Covalent radius in Angstroms.
- Type:
float
- velocity
3D velocity vector in Angstroms/ps.
- Type:
np.ndarray
- force
3D force vector for molecular dynamics.
- Type:
np.ndarray
- potential_energy
Potential energy contribution in Joules.
- Type:
float
- kinetic_energy
Kinetic energy in Joules.
- Type:
float
- metadata
Additional metadata for custom properties.
- Type:
Dict[str, Any]
- orbitals
List of atomic orbitals with quantum numbers.
- Type:
List[AtomicOrbital]
- bonds
List of bonds connected to this atom.
- Type:
List[GAM_Bond]
Examples
Basic atom creation: >>> atom = GAM_Atom(id=1, element=”C”, x=0.0, y=0.0, z=0.0) >>> print(atom.element) C
Advanced atom with charge and electronic state: >>> from ElectronicState import ElectronicState >>> charged_atom = GAM_Atom( … id=2, element=”O”, x=1.5, y=0.0, z=0.0, … charge=-0.5, electronic_state=ElectronicState.EXCITED_STATE … )
Distance calculation between atoms: >>> atom1 = GAM_Atom(id=1, element=”C”, x=0.0, y=0.0, z=0.0) >>> atom2 = GAM_Atom(id=2, element=”C”, x=1.54, y=0.0, z=0.0) >>> distance = atom1.calculate_distance_to(atom2) >>> print(f”Distance: {distance:.2f} Å”) Distance: 1.54 Å
Molecular dynamics velocity initialization: >>> atom = GAM_Atom(id=1, element=”H”, x=0.0, y=0.0, z=0.0) >>> atom.set_velocity_from_temperature(300.0) # 300 K >>> print(f”Velocity magnitude: {np.linalg.norm(atom.velocity):.3f} Å/ps”)
Notes
All positions are in Angstroms unless otherwise specified.
Charges are in elementary charge units (e).
Energies are calculated in Joules for physical accuracy.
The class automatically initializes atomic properties from reference data.
Bond management requires integration with GAM_Bond class.
- Raises:
ValueError – If element symbol is not found in periodic table reference data.
ValueError – If position vector has insufficient dimensions.
ValueError – If velocity array has incorrect shape or type.
See also
GAM_Bond: For bond representation and management. AtomicData: For periodic table reference data. ElectronicState: For electronic state enumeration.
- add_bond(bond)[source]
Adds a GAM_Bond object to the atom’s list of bonds.
- apply_force(force, dt)[source]
Apply force for time step dt using Velocity Verlet integration.
- apply_lennard_jones_potential(neighbor, epsilon, sigma)[source]
Calculates the Lennard-Jones potential energy with a neighbor atom.
- Parameters:
neighbor (
GAM_Atom) – The neighboring GAM_Atom.epsilon (
float) – The well depth of the potential.sigma (
float) – The distance at which the potential is zero.
- Return type:
float- Returns:
The Lennard-Jones potential energy contribution.
- calculate_angle(atom2, atom3)[source]
Calculate angle between three atoms (self-atom2-atom3) in degrees.
- Return type:
float
- calculate_coulomb_energy(neighbor)[source]
Calculates the electrostatic Coulomb energy between two atoms.
- Parameters:
neighbor (
GAM_Atom) – The neighboring GAM_Atom.- Return type:
float- Returns:
The electrostatic potential energy in Joules.
- calculate_dihedral(atom2, atom3, atom4)[source]
Calculate dihedral angle between four atoms.
- Return type:
float- Returns:
Dihedral angle in degrees
- calculate_distance_to(other)[source]
Calculate distance to another atom in Angstroms.
- Return type:
float
- calculate_electron_density(point)[source]
Calculate electron density at a point in space.
- Return type:
float
- calculate_electronegativity(scale='Pauling')[source]
Calculates or retrieves the atom’s electronegativity from a lookup table.
- Parameters:
scale (
str) – The electronegativity scale to use (‘Pauling’ or other).- Return type:
float- Returns:
The electronegativity value.
- calculate_improper(atom2, atom3, atom4)[source]
Calculate improper dihedral angle (atom1 is central).
- Return type:
float- Returns:
Improper angle in degrees
- calculate_kinetic_energy()[source]
Calculate kinetic energy in Joules.
- Return type:
float
- calculate_lennard_jones_energy(neighbor, epsilon, sigma)[source]
Calculates the Lennard-Jones potential energy with a neighbor atom.
- Parameters:
neighbor (
GAM_Atom) – The neighboring GAM_Atom.epsilon (
float) – The well depth of the potential (e.g., in Joules).sigma (
float) – The distance at which the potential is zero (e.g., in meters).
- Return type:
float- Returns:
The Lennard-Jones potential energy contribution in Joules.
- calculate_vdw_energy(neighbor, epsilon, sigma)[source]
Calculates the Van der Waals interaction energy using the Lennard-Jones potential.
- Parameters:
neighbor (
GAM_Atom) – The neighboring GAM_Atom.epsilon (
float) – The well depth of the potential, representing the strength of the interaction.sigma (
float) – The distance at which the potential is zero.
- Return type:
float- Returns:
The Van der Waals potential energy contribution in Joules.
- classmethod from_dict(data)[source]
Create atom instance from dictionary representation.
- Return type:
GAM_Atom
- classmethod from_json(filepath)[source]
Loads atom data from a JSON file and reconstructs the GAM_Atom object.
- Parameters:
filepath (
str) – The path to the input JSON file.- Return type:
GAM_Atom- Returns:
A new GAM_Atom object with the loaded data.
- get_bonding_partners()[source]
Returns a list of GAM_Atom objects this atom is bonded to.
- Return type:
List[GAM_Atom]
- NOTE: This requires a parent Molecule or System class to manage the full list of atoms.
The implementation here is a placeholder.
- get_bonds()[source]
Returns a list of all GAM_Bond objects connected to this atom.
- Return type:
List[GAM_Bond]
- get_neighbor_atoms(atoms)[source]
Returns a list of GAM_Atom objects directly connected via a bond.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
List[GAM_Atom]
- get_valence_electrons()[source]
Get the number of valence electrons for the atom.
- Return type:
int- Returns:
The number of valence electrons.
- inversion_center(center=None)[source]
Inverts the atom’s position through a central point.
- Parameters:
center (
Optional[ndarray]) – The center of inversion. If None, the origin is used.- Return type:
None
- is_bonded_to(other)[source]
Check if this atom is bonded to another atom.
- Return type:
bool
- mirror(plane_normal, plane_point=None)[source]
Reflects the atom’s position across a plane.
- Parameters:
plane_normal (
ndarray) – The normal vector of the reflection plane.plane_point (
Optional[ndarray]) – A point on the reflection plane. If None, the origin is used.
- Return type:
None
- property position: ndarray
Get position as numpy array.
- reflect(plane_normal)[source]
Reflect the atom through a plane defined by its normal vector.
- Parameters:
plane_normal (
ndarray) – Normal vector of the reflection plane- Return type:
None
- reflect_across_plane(plane_normal, plane_point=None)[source]
Reflects the atom’s position across a plane defined by its normal and a point.
- Parameters:
plane_normal (
ndarray) – The normal vector of the reflection plane.plane_point (
Optional[ndarray]) – A point on the reflection plane. If None, the origin is used.
- Return type:
None
- remove_bond(bond)[source]
Removes a GAM_Bond object from the atom’s list of bonds.
- rotate(rotation_matrix, center=None)[source]
Rotate the atom around a center point using a rotation matrix.
- Parameters:
rotation_matrix (
ndarray) – 3x3 rotation matrixcenter (
Optional[ndarray]) – Center of rotation (default is origin)
- Return type:
None
- rotate_around_axis(axis, angle_degrees, center=None)[source]
Rotate the atom around an arbitrary axis by a given angle.
- Parameters:
axis (
ndarray) – The axis of rotation (will be normalized)angle_degrees (
float) – Rotation angle in degreescenter (
Optional[ndarray]) – Center of rotation (default is origin)
- Return type:
None
- set_velocity_from_temperature(temperature_k)[source]
Sets the atom’s velocity based on a Maxwell-Boltzmann distribution for a given temperature.
- Parameters:
temperature_k (
float) – The desired temperature in Kelvin.- Return type:
None
- to_dict()[source]
Convert atom to dictionary representation.
- Return type:
Dict[str,Any]
- to_json(filepath)[source]
Saves the atom’s data to a JSON file.
- Parameters:
filepath (
str) – The path to the output JSON file.
- translate(vector)[source]
Translate the atom by a vector.
- Parameters:
vector (
ndarray) – Translation vector [dx, dy, dz]- Return type:
None
- property velocity: ndarray
Get velocity vector.
- class PyGamLab.structures.GAM_Bond(id, atom1_id, atom2_id, order=1)[source]
Bases:
objectAdvanced bond class for computational chemistry and molecular modeling applications.
The GAM_Bond class represents covalent bonds between atoms within molecular systems and provides comprehensive functionality for structural analysis, geometric calculations, and bond property evaluation. It supports various bond orders, strain energy calculations, and advanced geometric transformations essential for molecular dynamics simulations and quantum chemistry computations.
- id
Unique identifier for the bond within a molecular system.
- Type:
int
- atom1_id
ID of the first atom in the bond.
- Type:
int
- atom2_id
ID of the second atom in the bond.
- Type:
int
- order
Bond order (1=single, 2=double, 3=triple).
- Type:
int
- _length
Cached bond length in Angstroms.
- Type:
Optional[float]
- _energy
Cached bond energy in Joules.
- Type:
Optional[float]
Examples
Basic bond creation: >>> bond = GAM_Bond(id=1, atom1_id=1, atom2_id=2, order=1) >>> print(f”Bond order: {bond.order}”) Bond order: 1
Bond length calculation: >>> atoms = {1: GAM_Atom(1, “C”, 0.0, 0.0, 0.0), … 2: GAM_Atom(2, “C”, 1.54, 0.0, 0.0)} >>> bond = GAM_Bond(1, 1, 2, 1) >>> length = bond.calculate_length(atoms) >>> print(f”Bond length: {length:.2f} Å”) Bond length: 1.54 Å
Bond validation: >>> is_reasonable = bond.is_reasonable_length(atoms) >>> print(f”Reasonable bond length: {is_reasonable}”) Reasonable bond length: True
Strain energy calculation: >>> strain_energy = bond.calculate_strain_energy(atoms) >>> print(f”Strain energy: {strain_energy:.3f} kcal/mol”) Strain energy: 0.000 kcal/mol
Notes
Bond lengths are calculated in Angstroms.
Strain energies are calculated in kcal/mol using harmonic approximation.
Bond validation uses reference bond lengths with 20% tolerance.
All geometric calculations require access to the complete atom dictionary.
- Raises:
ValueError – If fixed atom ID in rotation operations is not part of the bond.
ValueError – If atoms associated with the bond do not exist in the provided dictionary.
See also
GAM_Atom: For individual atom representation and properties. GAM_Molecule: For complete molecular system management. REFERENCE_BOND_LENGTHS: For reference bond length data.
- property bond_vector: ndarray
Calculate the bond vector from atom1 to atom2.
- calculate_angle_with(other, atoms)[source]
Calculate angle between this bond and another bond.
- Parameters:
other (
GAM_Bond) – Another Bond objectatoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects
- Returns:
Angle in degrees between the bonds
- Return type:
float
- calculate_angle_with_plane(plane_normal, atoms)[source]
Calculates the angle between the bond vector and a user-defined plane.
- Parameters:
plane_normal (
ndarray) – The normal vector of the plane.atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.
- Return type:
float- Returns:
The angle in degrees.
- calculate_dihedral_angle(atom3_id, atom4_id, atoms)[source]
Calculates the dihedral angle between this bond and a plane defined by the third and fourth atoms.
- Parameters:
atom3_id (
int) – The ID of the third atom.atom4_id (
int) – The ID of the fourth atom.atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.
- Return type:
float- Returns:
The dihedral angle in degrees.
- calculate_length(atoms)[source]
Calculate the bond length in Angstroms.
- Return type:
float
- calculate_strain_energy(atoms)[source]
Calculate the strain energy of the bond based on deviation from ideal length.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects- Returns:
Strain energy in kcal/mol
- Return type:
float
- classmethod from_dict(data)[source]
Reconstructs a GAM_Bond object from a dictionary.
- Parameters:
data (
Dict[str,Any]) – A dictionary containing the bond’s data.- Return type:
GAM_Bond- Returns:
A new GAM_Bond object.
- get_atoms(atoms)[source]
Retrieves the two GAM_Atom objects connected by this bond.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
Tuple[GAM_Atom,GAM_Atom]- Returns:
A tuple containing the two GAM_Atom objects.
- get_bond_type(atoms)[source]
Returns a descriptive string for the bond type.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
str- Returns:
A string describing the bond (e.g., ‘C-C single bond’).
- get_elements(atoms)[source]
Returns a tuple of the elements involved in the bond.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
Tuple[str,str]- Returns:
A sorted tuple of the elements (e.g., (‘C’, ‘H’)).
- get_neighboring_bonds(atoms)[source]
Finds all other bonds that share an atom with this bond.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
List[GAM_Bond]- Returns:
A list of GAM_Bond objects that are neighbors to this bond.
- is_aromatic(atoms)[source]
Checks if the bond is likely part of an aromatic system. This is a simple heuristic based on bond order and element types.
- Parameters:
atoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objects.- Return type:
bool- Returns:
True if the bond is aromatic, False otherwise.
- is_part_of_ring(atoms, max_ring_size=7)[source]
- Return type:
bool
Checks if the bond is part of a closed ring structure using Breadth-First Search (BFS). …
- is_reasonable_length(atoms)[source]
- Return type:
bool
Check if the bond length is reasonable based on reference data. …
- rotate_around_axis(axis, angle_degrees, atoms, fixed_atom_id=None)[source]
Rotate the bond around an axis while keeping one atom fixed.
- Parameters:
axis (
ndarray) – Rotation axisangle_degrees (
float) – Rotation angle in degreesatoms (
Dict[int,GAM_Atom]) – Dictionary mapping atom IDs to Atom objectsfixed_atom_id (
Optional[int]) – ID of the atom to keep fixed (defaults to atom1_id)
- Return type:
None
- to_dict()[source]
Serializes the bond’s data into a dictionary.
- Return type:
Dict[str,Any]- Returns:
A dictionary representation of the bond.
- to_json(filepath)[source]
Saves the bond’s data to a JSON file.
- Parameters:
filepath (
str) – The path to the output JSON file.
- class PyGamLab.structures.GAM_Molecule(atoms=<factory>, bonds=<factory>)[source]
Bases:
objectAdvanced molecule class for computational chemistry and molecular modeling applications.
The GAM_Molecule class represents complete molecular systems and provides comprehensive functionality for molecular analysis, geometric calculations, and structural properties. It manages collections of atoms and bonds, enabling sophisticated molecular dynamics simulations, quantum chemistry computations, and structural analysis workflows.
- atoms
Dictionary mapping atom IDs to GAM_Atom objects.
- Type:
Dict[int, GAM_Atom]
- bonds
Dictionary mapping bond IDs to GAM_Bond objects.
- Type:
Dict[int, GAM_Bond]
Examples
Basic molecule creation: >>> molecule = GAM_Molecule() >>> atom1 = GAM_Atom(id=1, element=”C”, x=0.0, y=0.0, z=0.0) >>> atom2 = GAM_Atom(id=2, element=”C”, x=1.54, y=0.0, z=0.0) >>> molecule.add_atom(atom1) >>> molecule.add_atom(atom2) >>> print(f”Atoms: {len(molecule.atoms)}”) Atoms: 2
Molecular properties: >>> formula = molecule.get_molecular_formula() >>> mass = molecule.calculate_molecular_mass() >>> print(f”Formula: {formula}, Mass: {mass:.2f} amu”) Formula: C2, Mass: 24.02 amu
Geometric analysis: >>> com = molecule.get_center_of_mass() >>> cog = molecule.get_center_of_geometry() >>> print(f”Center of mass: {com}”) >>> print(f”Center of geometry: {cog}”) Center of mass: [0.77 0. 0. ] Center of geometry: [0.77 0. 0. ]
Energy calculations: >>> lj_energy = molecule.calculate_total_lennard_jones_energy() >>> coulomb_energy = molecule.calculate_total_coulomb_energy() >>> print(f”LJ Energy: {lj_energy:.2e} J”) >>> print(f”Coulomb Energy: {coulomb_energy:.2e} J”) LJ Energy: -2.34e-21 J Coulomb Energy: 0.00e+00 J
Structure validation: >>> issues = molecule.validate_structure() >>> print(f”Validation issues: {issues}”) Validation issues: {‘unreasonable_bonds’: [], ‘isolated_atoms’: [], …}
Notes
All positions are in Angstroms unless otherwise specified.
Energies are calculated in Joules for physical accuracy.
The class automatically manages bond-atom relationships when bonds are added.
Ring detection uses depth-first search with configurable maximum ring size.
Structure validation checks for common molecular geometry issues.
- Raises:
KeyError – If referenced atoms do not exist when adding bonds.
ValueError – If atom or bond IDs are not unique.
See also
GAM_Atom: For individual atom representation and properties. GAM_Bond: For bond representation and analysis. REFERENCE_BOND_LENGTHS: For reference bond length data. REFERENCE_VALENCE_ELECTRONS: For valence electron reference data.
- add_atom(atom)[source]
Adds an atom to the molecule.
- add_bond(bond)[source]
Adds a bond to the molecule and updates the atoms’ bond lists.
- align_to_principal_axes()[source]
Align the molecule to its principal axes of inertia.
- Return type:
None
-
atoms:
Dict[int,GAM_Atom]
-
bonds:
Dict[int,GAM_Bond]
- calculate_bond_strain_energy()[source]
Calculate total bond strain energy.
- Return type:
float- Returns:
Total strain energy in kcal/mol.
- calculate_dipole_moment()[source]
Calculate the electric dipole moment of the molecule.
- Return type:
ndarray- Returns:
Dipole moment vector in Debye units.
- calculate_molecular_mass()[source]
Calculate the total molecular mass in atomic mass units.
- Return type:
float- Returns:
Total molecular mass in amu.
- calculate_moment_of_inertia_tensor()[source]
Calculate the moment of inertia tensor of the molecule.
- Return type:
ndarray- Returns:
3x3 moment of inertia tensor.
- calculate_radius_of_gyration()[source]
Calculate the radius of gyration of the molecule.
- Return type:
float- Returns:
Radius of gyration in Angstroms.
- calculate_total_coulomb_energy()[source]
Calculate total electrostatic energy for all atom pairs.
- Return type:
float- Returns:
Total Coulomb energy in Joules.
- calculate_total_energy()[source]
Calculates the total energy of the molecule (placeholder).
- Return type:
float
- calculate_total_lennard_jones_energy(epsilon=1e-21, sigma=3.4e-10)[source]
Calculate total Lennard-Jones energy for all non-bonded atom pairs.
- Parameters:
epsilon (
float) – Well depth parameter (J).sigma (
float) – Distance parameter (m).
- Return type:
float- Returns:
Total Lennard-Jones energy in Joules.
- find_atoms_by_element(element)[source]
Find all atoms of a specific element.
- Parameters:
element (
str) – Element symbol (e.g., ‘C’, ‘H’, ‘O’).- Return type:
List[GAM_Atom]- Returns:
List of atoms of the specified element.
- find_rings(max_ring_size=12)[source]
Find all rings in the molecule using depth-first search.
- Parameters:
max_ring_size (
int) – Maximum ring size to search for.- Return type:
List[List[int]]- Returns:
List of rings, where each ring is a list of atom IDs.
- find_shortest_path(atom1_id, atom2_id)[source]
Find the shortest path between two atoms through bonds.
- Parameters:
atom1_id (
int) – Starting atom ID.atom2_id (
int) – Target atom ID.
- Return type:
Optional[List[int]]- Returns:
List of atom IDs representing the shortest path, or None if no path exists.
- classmethod from_dict(data)[source]
Create molecule from dictionary representation.
- Parameters:
data (
Dict[str,Any]) – Dictionary containing molecule data.- Return type:
GAM_Molecule- Returns:
New GAM_Molecule instance.
- get_atom(atom_id)[source]
Retrieves an atom by its ID.
- Return type:
Optional[GAM_Atom]
- get_bond(bond_id)[source]
Retrieves a bond by its ID.
- Return type:
Optional[GAM_Bond]
- get_bounding_box()[source]
Calculate the bounding box of the molecule.
- Return type:
Tuple[ndarray,ndarray]- Returns:
Tuple of (min_coords, max_coords) as numpy arrays.
- get_center_of_geometry()[source]
Calculate the geometric center (centroid) of the molecule.
- Return type:
ndarray- Returns:
The geometric center coordinates as a numpy array.
- get_center_of_mass()[source]
Calculate the center of mass of the molecule.
- Return type:
ndarray- Returns:
The center of mass coordinates as a numpy array.
- get_connectivity_matrix()[source]
Generate the connectivity matrix for the molecule.
- Return type:
ndarray- Returns:
N×N connectivity matrix where N is the number of atoms.
- get_distance_matrix()[source]
Calculate the distance matrix between all atoms.
- Return type:
ndarray- Returns:
N×N distance matrix in Angstroms.
- get_molecular_formula()[source]
Generate the molecular formula string.
- Return type:
str- Returns:
Molecular formula (e.g., “C6H12O6”).
- get_principal_moments()[source]
Calculate principal moments of inertia and axes.
- Return type:
Tuple[ndarray,ndarray]- Returns:
Tuple of (eigenvalues, eigenvectors) representing principal moments and axes.
- rotate_molecule(rotation_matrix, center=None)[source]
Rotate the entire molecule around a center point.
- Parameters:
rotation_matrix (
ndarray) – 3×3 rotation matrix.center (
Optional[ndarray]) – Center of rotation (default is center of mass).
- Return type:
None
- to_ase_object()[source]
- to_dict()[source]
Convert molecule to dictionary representation.
- Return type:
Dict[str,Any]- Returns:
Dictionary representation of the molecule.
- to_pymatgen_object()[source]
- to_xyz_file(filepath, comment='Generated by PyGamlab')[source]
Write molecule to XYZ format file.
- Parameters:
filepath (
str) – Output file path.comment (
str) – Comment line for the XYZ file.
- Return type:
None
- translate_molecule(vector)[source]
Translate the entire molecule by a vector.
- Parameters:
vector (
ndarray) – Translation vector [dx, dy, dz].- Return type:
None
- validate_structure()[source]
Validate the molecular structure and return potential issues.
- Return type:
Dict[str,List[str]]- Returns:
Dictionary with categories of issues found.
- class PyGamLab.structures.Graphene(lattice_constant=2.46, width=10.0, length=10.0, edge_type='armchair', rotation=0.0, vacuum=10.0, origin=(0.0, 0.0))[source]
Bases:
objectClass for constructing and manipulating monolayer graphene nanostructures.
This class provides a flexible framework for generating both periodic graphene unit cells and finite graphene flakes with customizable geometries, edge terminations, and orientations. The implementation is suitable for atomistic modeling, visualization, and export to external simulation packages (e.g., ASE, LAMMPS, Quantum ESPRESSO).
- The Graphene class supports:
Generation of primitive unit cells or finite flakes with armchair or zigzag edges.
Parameterized lattice constant, width, and length.
Structural transformations such as translation and rotation.
Automatic bond construction via nearest-neighbor detection.
Export of atomic configurations to .xyz files or ASE objects.
- This class is designed to be extendable for modeling:
Multilayer graphene and heterostructures
Point or line defects (vacancies, dopants, grain boundaries)
Strained or rotated configurations (e.g., twisted bilayers)
Functionalized graphene or 2D carbon allotropes
- Parameters:
lattice_constant (float, optional) – Lattice constant of graphene in Ångströms (default: 2.46 Å).
width (float, optional) – Width of the graphene flake (in Å) along the x-direction (default: 10.0 Å).
length (float, optional) – Length of the graphene flake (in Å) along the y-direction (default: 10.0 Å).
edge_type (str, optional) – Edge termination type, either
'armchair'or'zigzag'(default: ‘armchair’).rotation (float, optional) – Rotation angle of the entire structure (in degrees) about the z-axis (default: 0.0°).
vacuum (float, optional) – Extra spacing in the z-direction (useful for periodic boundary simulations) (default: 10.0 Å).
origin (tuple of float, optional) – (x, y) coordinates of the origin shift (default: (0.0, 0.0)).
- atoms
List of carbon atoms in the graphene structure.
- Type:
list of GAM_Atom
- bonds
List of covalent C–C bonds identified via nearest-neighbor search.
- Type:
list of GAM_Bond
- lattice_vectors
Lattice vectors of the graphene unit cell.
- Type:
ndarray of shape (2, 3)
- meta
Metadata dictionary storing structure parameters and build status.
- Type:
dict
- origin
Cartesian coordinates of the structure’s reference origin.
- Type:
tuple of float
- build() Graphene[source]
Constructs the graphene lattice based on current parameters.
- translate(dx, dy, dz=0.0)[source]
Translates all atoms by the specified displacement vector.
- rotate(angle_deg, about_center=True)[source]
Rotates the structure around the z-axis.
- nearest_neighbors(r_cut=None) Graphene[source]
Generates C–C bonds using a cutoff-based nearest-neighbor criterion.
- get_atoms() list[GAM_Atom][source]
Returns a deep copy of the atomic list.
- get_positions() list[tuple[float, float, float]][source]
Returns a list of atomic coordinates.
- get_elements() list[str][source]
Returns a list of element symbols (typically all ‘C’).
- copy() Graphene[source]
Returns a deep copy of the current graphene structure.
- to_xyz(path: str)[source]
Writes the atomic configuration to an XYZ file.
- to_ase() ase.Atoms or None[source]
Exports the structure as an ASE Atoms object (if ASE is installed).
Notes
The graphene lattice constant (2.46 Å) corresponds to a C–C bond length of approximately 1.42 Å.
The structure is generated in the xy-plane with z = 0 for all atoms.
Rotation and translation are applied after flake construction.
For periodic systems, the vacuum spacing ensures minimal z-overlap between layers.
Examples
>>> g = Graphene(width=20.0, length=15.0, edge_type='zigzag', rotation=15) >>> g.build() >>> g.to_xyz('graphene_flake.xyz') >>> atoms = g.to_ase() >>> print(len(atoms), "atoms in graphene flake")
- build()[source]
Construct the graphene structure based on parameters.
- Return type:
Graphene- Returns:
Self for method chaining
- copy()[source]
Create deep copy of the structure.
- Return type:
Graphene
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- nearest_neighbors(r_cut=None)[source]
Build bonds based on nearest neighbor distances.
- Parameters:
r_cut (
Optional[float]) – Distance cutoff for bonding (default: 1.6 * C-C bond length)- Return type:
Graphene- Returns:
Self for method chaining
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Return type:
Optional[Atoms]- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Nano_OneD_Builder(material, structure_type, lattice_constant=None, crystal_structure='fcc', direction=(1, 0, 0), radius=1.0, length=5.0, vacuum=10.0, **kwargs)[source]
Bases:
objectBuilder class for 1D nanomaterials such as nanowires, nanorods, and nanotubes.
This class provides flexible tools to construct, modify, and export one-dimensional nanostructures based on atomic-scale models. It supports metallic, semiconductor, and carbon-based nanostructures, including multi-walled carbon nanotubes (MWCNTs), nanowire arrays, and nanotube bundles.
Structures can be generated from ASE’s bulk and nanotube generators, and then modified using defect insertion, alloying, or strain application. The generated geometries can be exported in multiple formats (XYZ, CIF, PDB, etc.) or directly returned as ASE Atoms objects or GAM-compatible atom lists.
- Parameters:
material (str) – Chemical symbol of the element (e.g., “Au”, “C”, “Si”).
structure_type (str) – Type of nanostructure to generate: one of
"nanowire","nanorod", or"nanotube".lattice_constant (float, optional) – Lattice constant of the bulk crystal in Ångströms. Required for crystalline materials other than carbon nanotubes.
crystal_structure (str, default="fcc") – ASE bulk structure type (e.g.,
"fcc","bcc","hcp","diamond").direction (tuple of int, default=(1, 0, 0)) – Miller indices defining the nanowire growth direction.
radius (float, default=1.0) – Radius of the 1D structure in nanometers.
length (float, default=5.0) – Length of the structure in nanometers.
vacuum (float, default=10.0) – Vacuum spacing in Ångströms.
**kwargs – Additional parameters reserved for future extensions.
- ASE_atoms
The atomic structure generated using ASE.
- Type:
ase.Atoms
- atoms
List of atoms in GAM-compatible format.
- Type:
list of GAM_Atom
- meta
Metadata describing structure parameters.
- Type:
dict
- structure_type
The chosen type of nanostructure (“nanowire”, “nanorod”, or “nanotube”).
- Type:
str
- direction
Growth direction (Miller indices).
- Type:
tuple of int
- radius, length, vacuum
Structural dimensions and vacuum spacing.
- Type:
float
Notes
Nanotubes are generated using ASE’s ase.build.nanotube() function.
Nanowires/nanorods are cut from bulk crystals and shaped cylindrically.
All distances are internally converted to Ångströms.
The builder can introduce defects, create alloys, or apply strain to simulate realistic material behavior.
Examples
>>> builder = Nano_OneD_Builder(material="Au", structure_type="nanowire", ... lattice_constant=4.08, crystal_structure="fcc", ... radius=1.5, length=10.0) >>> builder.add_defects(defect_type="vacancy", concentration=0.02) >>> builder.apply_strain(0.05, direction='z') >>> builder.export("gold_nanowire", formats=['xyz', 'cif']) >>> ase_atoms = builder.to_ase()
- add_defects(defect_type='vacancy', concentration=0.05, seed=None, min_distance=2.0)[source]
Add defects to the structure.
Parameters:¶
- defect_typestr
Type of defect (‘vacancy’, ‘interstitial’)
- concentrationfloat
Concentration of defects (0-1)
- seedint
Random seed for reproducibility
- min_distancefloat
Minimum distance between atoms for interstitial defects (in Angstroms)
- apply_strain(strain, direction='z')[source]
Apply strain to the structure.
Parameters:¶
- strainfloat
Strain value (positive for tension, negative for compression)
- directionstr
Direction to apply strain (‘x’, ‘y’, or ‘z’)
- copy()[source]
Create a deep copy of the structure.
- create_alloy(elements, concentrations, seed=None)[source]
Create an alloy by replacing atoms with different elements.
Parameters:¶
- elementslist
List of element symbols to add
- concentrationslist
List of concentrations for each element (should sum to <= 1)
- seedint
Random seed for reproducibility
- create_multiple_nanowires(num_wires, spacing=2.0, arrangement='linear', **wire_params)[source]
Create multiple parallel nanowires/nanorods arranged in a specific pattern.
Parameters:¶
- num_wiresint
Number of nanowires to create
- spacingfloat
Spacing between wires in nanometers
- arrangementstr
Arrangement pattern (‘linear’, ‘hexagonal’, ‘square’)
- wire_paramsdict
Parameters to pass to create() method for each wire
Returns:¶
: ase.atoms.Atoms
Combined structure of multiple nanowires
- create_mwcnt(num_walls, initial_n=6, initial_m=6, wall_spacing=0.34, length=10.0, vacuum=10.0)[source]
Create a multi-walled carbon nanotube (MWCNT) with concentric tubes.
Parameters:¶
- num_wallsint
Number of walls in the MWCNT
- initial_n, initial_mint
Chiral indices for the innermost tube
- wall_spacingfloat
Spacing between walls in nm (default 0.34 nm, typical for graphite)
- lengthfloat
Length of the MWCNT in nm
- vacuumfloat
Vacuum spacing in Angstroms
Returns:¶
: ase.atoms.Atoms
Multi-walled carbon nanotube structure with concentric tubes
- create_nanotube_bundle(num_tubes, tube_type='SWCNT', arrangement='hexagonal', spacing=0.34, **tube_params)[source]
Create a bundle of carbon nanotubes arranged in a specific pattern.
Parameters:¶
- num_tubesint
Number of tubes in the bundle
- tube_typestr
Type of tubes (‘SWCNT’ or ‘MWCNT’)
- arrangementstr
Arrangement pattern (‘hexagonal’, ‘square’, ‘circular’)
- spacingfloat
Spacing between tubes in nm
- tube_paramsdict
Parameters for tube creation (passed to create() or create_mwcnt())
Returns:¶
: ase.atoms.Atoms
Bundle of nanotubes
- export(filename, formats=None, trajectory=False, frame_interval=1)[source]
Export structure in various formats with additional options.
Parameters:¶
- filenamestr
Base filename without extension
- formatslist
List of format strings (default: [‘xyz’, ‘cif’, ‘vasp’, ‘pdb’])
- trajectorybool
Whether to save as trajectory (useful for dynamics)
- frame_intervalint
Interval between frames for trajectory
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Return type:
Optional[Atoms]- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Nano_TwoD_Builder(material, structure_type)[source]
Bases:
objectComprehensive builder for 2D nanomaterials such as nanosheets, monolayers, and van der Waals heterostructures.
The Nano_TwoD_Builder class provides an advanced atomistic modeling framework for constructing two-dimensional (2D) nanostructures, including:
Nanosheets: elemental or binary 2D lattices (e.g., graphene, silicene, phosphorene)
Transition Metal Dichalcogenides (TMDs): MX₂ layered compounds with tunable 1T/2H phases
Heterostructures: stacked multilayer systems with controlled interlayer spacing
The builder supports both honeycomb-like (graphene family) and layered (TMD) topologies. It integrates with ASE’s graphene() and mx2() generators and enables direct conversion to GAM-compatible formats for downstream simulation pipelines.
Features¶
Generate 2D nanosheets and TMD monolayers
Build van der Waals heterostructures from arbitrary combinations of layers
Support for custom formulas, lattice constants, and layer thicknesses
Predefined constructors for common 2D materials (graphene, MoS₂, WS₂, etc.)
ASE-based export and visualization (XYZ, CIF, PDB)
Structure translation and rotation operations
GAM-compatible atom and bond representation
- type material:
str- param material:
Name or symbol of the 2D material (e.g., “graphene”, “MoS2”, “BN”).
- type material:
str
- type structure_type:
str- param structure_type:
Type of 2D nanostructure to build.
- type structure_type:
{‘nanosheet’, ‘tmd’}
- ASE_atoms
Underlying ASE structure representing the generated material.
- Type:
ase.Atoms
- atoms
List of atoms in GAM-compatible format.
- Type:
list[GAM_Atom]
- bonds
Optional list of identified bonds.
- Type:
list[GAM_Bond]
- layered_materials
Database of transition metal dichalcogenides (TMDs) and related 2D materials.
- Type:
dict
- nanosheet_materials
Database of single-element or binary 2D sheet materials.
- Type:
dict
- meta
Metadata dictionary containing build parameters and structure details.
- Type:
dict
- structure_type
Selected structure type (‘nanosheet’ or ‘tmd’).
- Type:
str
- material
Material name used for generation.
- Type:
str
- create_layered_material(phase='2H', size=(10, 10, 1), vacuum=10.0, ...)[source]
Build a TMD or layered 2D material (e.g., MoS₂, WSe₂) using ASE’s mx2() function.
- create_nanosheet(size=(10, 10, 1), vacuum=10.0, ...)[source]
Build a honeycomb-like nanosheet (e.g., graphene, silicene) using ASE’s graphene() function.
- create_layered_heterostructure(materials_and_phases, layer_spacing=6.5, ...)[source]
Stack multiple TMD layers with custom interlayer spacing.
- create_nanosheet_heterostructure(materials, layer_spacing=3.4, ...)[source]
Build van der Waals heterostructures combining 2D sheets (e.g., graphene/hBN).
- create_custom_sheet(formula, lattice_constant, thickness=0.0, ...)[source]
Define a custom 2D lattice from scratch.
- list_layered_materials(category=None)[source]
Display all available layered (TMD) materials in the internal database.
- list_nanosheet_materials()[source]
Display all available 2D sheet materials and their physical properties.
- translate(dx, dy, dz=0.0)[source]
Translate atomic coordinates in 3D space.
- rotate(angle_deg, about_center=True)[source]
Rotate the sheet around the z-axis (in-plane rotation).
- copy()[source]
Deep copy the atomic structure and metadata.
- get_atoms()[source]
Return a deep copy of all atoms as GAM_Atom objects.
- get_positions()[source]
Retrieve atomic positions as (x, y, z) tuples.
- get_elements()[source]
Return list of atomic symbols.
- to_xyz(filename)[source]
Export structure to .xyz file format.
- to_ase()[source]
Convert to an ASE Atoms object for external use.
Notes
The builder automatically selects between graphene() and mx2() constructors based on the specified structure_type.
Both nanosheet and layered materials can be stacked into heterostructures with adjustable vacuum spacing and interlayer distances.
Built-in materials include metallic, semiconducting, and superconducting 2D systems: MoS₂, WS₂, MoSe₂, WSe₂, NbSe₂, TaSe₂, PtS₂, CrI₃, graphene, silicene, BN, phosphorene, etc.
The meta dictionary records all parameters used in construction, enabling reproducibility and dataset traceability.
All units are expressed in Ångströms unless otherwise noted.
Examples
>>> from pygamlab import Nano_TwoD_Builder
>>> # 1. Generate a graphene sheet >>> sheet = Nano_TwoD_Builder(material="graphene", structure_type="nanosheet") >>> sheet.to_xyz("graphene.xyz")
>>> # 2. Build a MoS2 monolayer in the 2H phase >>> tmd = Nano_TwoD_Builder(material="MoS2", structure_type="tmd") >>> tmd.create_layered_material(phase='2H', size=(5,5,1), vacuum=15.0) >>> tmd.to_xyz("MoS2_2H.xyz")
>>> # 3. Construct a van der Waals heterostructure: Graphene/hBN >>> het = Nano_TwoD_Builder(material="graphene", structure_type="nanosheet") >>> het.create_nanosheet_heterostructure(["graphene", "boron_nitride"], layer_spacing=3.35) >>> het.to_xyz("graphene_hbn_heterostructure.xyz")
>>> # 4. Create a custom 2D material >>> custom = Nano_TwoD_Builder(material="CustomX", structure_type="nanosheet") >>> custom.create_custom_sheet(formula="X2", lattice_constant=3.6, thickness=0.2) >>> custom.to_xyz("CustomX_sheet.xyz")
- antimonene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create antimonene nanosheet.
- arsenene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create arsenene nanosheet.
- boron_nitride_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create hexagonal boron nitride nanosheet.
- copy()[source]
Create a deep copy of the structure.
- create_custom_sheet(formula, lattice_constant, thickness=0.0, size=(1, 1, 1), vacuum=10.0)[source]
Create a custom nanosheet with specified parameters.
- Parameters:
formula (str) – Chemical formula (e.g., ‘C2’, ‘Si2’, ‘BN’)
lattice_constant (float) – Lattice constant in Angstrom
thickness (float) – Thickness/buckling parameter
size (tuple) – Supercell size
vacuum (float, optional) – Vacuum spacing
- Returns:
Custom nanosheet structure
- Return type:
Atoms
- create_layered_heterostructure(materials_and_phases, layer_spacing=6.5, size=(1, 1, 1), vacuum=10.0)[source]
Create a heterostructure from multiple layered materials.
- Parameters:
materials_and_phases (list) – List of tuples: [(material, phase), …] or list of material names
layer_spacing (float) – Distance between layers
size (tuple) – Supercell size
vacuum (float, optional) – Total vacuum spacing
- Returns:
Heterostructure
- Return type:
Atoms
- create_layered_material(phase=None, size=(10, 10, 1), vacuum=10.0, custom_formula=None, custom_lattice_constant=None, custom_thickness=None)[source]
Create a layered material using the ASE mx2 function.
- Parameters:
material (str) – Material name from database
phase (str, optional) – Crystal phase (‘2H’ or ‘1T’). Uses preferred phase if None.
size (tuple) – Supercell size (nx, ny, nz)
vacuum (float, optional) – Vacuum spacing in z-direction
custom_formula (str, optional) – Override default formula
custom_lattice_constant (float, optional) – Override default lattice constant
custom_thickness (float, optional) – Override default thickness
- Returns:
Layered material structure
- Return type:
Atoms
- create_nanosheet(size=(10, 10, 1), vacuum=10.0, custom_formula=None, custom_lattice_constant=None, custom_thickness=None)[source]
Create a nanosheet using the ASE graphene function with modified parameters.
- Parameters:
material (str) – Material name from the database
size (tuple) – Supercell size (nx, ny, nz)
vacuum (float, optional) – Vacuum spacing in z-direction
custom_formula (str, optional) – Override the default formula
custom_lattice_constant (float, optional) – Override the default lattice constant
custom_thickness (float, optional) – Override the default thickness
- Returns:
ASE Atoms object of the nanosheet
- Return type:
Atoms
- create_nanosheet_heterostructure(materials, layer_spacing=3.4, size=(1, 1, 1), vacuum=10.0)[source]
Create a heterostructure by stacking different materials.
- Parameters:
materials (list) – List of material names to stack
layer_spacing (float) – Distance between layers in Angstrom
size (tuple) – Supercell size for each layer
vacuum (float, optional) – Total vacuum spacing
- Returns:
Heterostructure combining multiple materials
- Return type:
Atoms
- cri3_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- germanene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create germanene nanosheet.
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- graphene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create graphene nanosheet.
- list_layered_materials(category=None)[source]
Display available materials.
- Parameters:
category (str, optional) – Filter by category (‘tmd’, ‘halide’, ‘topological’, etc.)
- Return type:
None
- list_nanosheet_materials()[source]
Display all available materials and their properties.
- Return type:
None
- mos2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
Create MoS2 sheet.
- mose2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- nbse2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- phosphorene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create phosphorene nanosheet (honeycomb approximation).
- pts2_sheet(phase='1T', size=(1, 1, 1), vacuum=10.0)[source]
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- silicene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create silicene nanosheet.
- stanene_sheet(size=(1, 1, 1), vacuum=10.0)[source]
Create stanene nanosheet.
- tase2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Return type:
Optional[Atoms]- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- ws2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- wse2_sheet(phase='2H', size=(1, 1, 1), vacuum=10.0)[source]
- class PyGamLab.structures.Nano_ZeroD_Builder(material, structure_type, size, crystal_structure='fcc', lattice_constant=None, vacuum=10.0, surfaces=None, surface_energies=None, noshells=None, radius_type='sphere', **kwargs)[source]
Bases:
objectHigh-level atomistic builder for 0D nanostructures.
The Nano_ZeroD_Builder class provides a unified interface for constructing atomistic models of zero-dimensional (0D) nanostructures, including:
Quantum dots (semiconducting nanocrystals with quantum confinement)
Nanoclusters (small metallic or covalent atomic clusters)
Nanoparticles (larger crystalline particles, optionally faceted using Wulff construction)
This class supports both geometric and crystallographic control, allowing for the creation of realistic nanoscale systems based on their lattice type, surface facets, and atomic arrangement. The resulting structures can be used as input for DFT, MD, or ML simulations.
Features¶
Build 0D nanostructures from bulk crystals or predefined motifs
Support for FCC, BCC, HCP, diamond, zincblende, and related lattices
Integration with ASE (Atomic Simulation Environment)
Alloy, defect, and strain engineering
Ligand surface functionalization
Core–shell nanoparticle generation
Randomized variation generation for dataset expansion
- type material:
str- param material:
Chemical symbol of the primary element (e.g., ‘Au’, ‘CdSe’).
- type material:
str
- type structure_type:
str- param structure_type:
Type of nanostructure to build.
- type structure_type:
{‘quantum_dot’, ‘nanocluster’, ‘nanoparticle’}
- type size:
float- param size:
- Size parameter — interpreted as:
Radius (Å) for quantum dots or nanoparticles
Number of atomic shells for nanoclusters
- type size:
float
- type crystal_structure:
str- param crystal_structure:
Underlying lattice type. Defaults to ‘fcc’.
- type crystal_structure:
str, optional
- type lattice_constant:
float- param lattice_constant:
Lattice constant in Ångströms. Required for bulk-based generation.
- type lattice_constant:
float, optional
- type vacuum:
float- param vacuum:
Vacuum spacing around the nanostructure (Å). Default is 10.0 Å.
- type vacuum:
float, optional
- type surfaces:
- param surfaces:
Miller indices of the surfaces for Wulff construction (only for nanoparticles).
- type surfaces:
list of tuple[int], optional
- type surface_energies:
- param surface_energies:
Surface energies (J/m²) corresponding to surfaces.
- type surface_energies:
list of float, optional
- type noshells:
int- param noshells:
Number of shells for nanocluster structures (if not using size).
- type noshells:
int, optional
- type radius_type:
str- param radius_type:
Defines the nanoparticle geometry. Currently only ‘sphere’ is supported.
- type radius_type:
{‘sphere’}, optional
- type **kwargs:
- param **kwargs:
Additional keyword arguments passed to ASE structure constructors.
- type **kwargs:
dict
- ASE_atoms
The underlying ASE Atoms object representing the structure.
- Type:
ase.Atoms
- atoms
A list of GAM_Atom objects for GAM-Lab compatibility.
- Type:
list[GAM_Atom]
- bonds
List of identified bonds (if applicable).
- Type:
list[GAM_Bond]
- meta
Metadata dictionary containing build parameters and history.
- Type:
dict
- structure_type
Type of structure (‘quantum_dot’, ‘nanocluster’, ‘nanoparticle’).
- Type:
str
- radius_type
Shape type used for spherical generation.
- Type:
str
- create_alloy(elements, compositions)[source]
Randomly substitutes atomic species to generate alloyed structures.
- add_defects(defect_type, concentration, elements=None)[source]
Introduce vacancies, interstitials, or substitutional defects.
- create_variations(base_structure, size_range, n_structures, \*\*kwargs)[source]
Generate multiple structural variations within a size range.
- apply_strain(strain, direction='xyz')[source]
Apply uniaxial or isotropic strain to the structure.
- modify_surface(ligands, coverage=1.0)[source]
Add ligand atoms to surface sites for surface modification.
- create_core_shell(core_material, shell_material, shell_thickness, shell_lattice_constant=None)[source]
Create a core–shell nanostructure by wrapping the core with another material.
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by a specified vector.
- rotate(angle_deg, about_center=True)[source]
Rotate the structure about the z-axis or its center of mass.
- copy()[source]
Create a deep copy of the structure.
- get_atoms()[source]
Return a copy of the GAM_Atom list.
- get_positions()[source]
Return atomic positions as a list of (x, y, z) tuples.
- get_elements()[source]
Return a list of atomic symbols.
- _to_GAM_Atoms(atoms)[source]
Internal conversion from ASE atoms to GAM_Atom objects.
Notes
The generated nanostructures can serve as initial geometries for relaxation, energy minimization, or electronic structure calculations.
Surface atoms are automatically centered with optional vacuum padding.
The Wulff construction minimizes total surface energy for given facets.
Alloying, defect creation, and surface modification are stochastic; use a fixed random seed for reproducibility.
The core–shell builder assumes isotropic growth; anisotropic extension can be implemented by modifying the shell generator.
Examples
>>> from pygamlab import Nano_ZeroD_Builder >>> # Generate a gold nanocluster with 5 atomic shells >>> builder = Nano_ZeroD_Builder(material='Au', structure_type='nanocluster', size=5) >>> atoms = builder.ASE_atoms >>> builder.to_xyz('Au_cluster.xyz')
>>> # Build a 3 nm CdSe quantum dot >>> qd = Nano_ZeroD_Builder(material='CdSe', structure_type='quantum_dot', ... crystal_structure='zincblende', ... lattice_constant=6.08, size=15.0) >>> qd.apply_strain(0.02) >>> qd.to_xyz('CdSe_QD_strained.xyz')
>>> # Create a core–shell Ag@Au nanoparticle >>> cs = Nano_ZeroD_Builder(material='Ag', structure_type='nanoparticle', ... size=25.0, surfaces=[(1, 1, 1), (1, 0, 0)], ... surface_energies=[1.2, 1.5]) >>> cs.create_core_shell(core_material='Ag', shell_material='Au', shell_thickness=5.0) >>> cs.to_xyz('AgAu_core_shell.xyz')
- add_defects(defect_type, concentration, elements=None)[source]
Add defects to the structure.
- Parameters:
defect_type (
str) – ‘vacancy’, ‘interstitial’, or ‘substitution’concentration (
float) – Defect concentration (0-1)elements (
List[str]) – Elements for substitution/interstitial
- Return type:
GAM_Atom- Returns:
Structure with defects
- apply_strain(strain, direction='xyz')[source]
Apply strain to the structure.
- Parameters:
atoms – Input structure
strain (
float) – Strain factor (positive for tension, negative for compression)direction (
str) – Direction(s) to apply strain
- Return type:
GAM_Atom- Returns:
Strained structure
- copy()[source]
Create a deep copy of the structure.
- create_alloy(elements, compositions)[source]
Create an alloy by randomly substituting atoms.
- Parameters:
base_atoms – Base structure
elements (
List[str]) – List of elements to includecompositions (
List[float]) – Corresponding atomic fractions
- Return type:
GAM_Atom- Returns:
Alloyed structure
- create_core_shell(core_material, shell_material, shell_thickness, shell_lattice_constant=None)[source]
Create a core-shell nanostructure.
- Parameters:
core_material (
str) – Material for the core (e.g., “Au”, “CdSe”)shell_material (
str) – Material for the shell (e.g., “Ag”, “CdS”)shell_thickness (
float) – Thickness of the shell in Åshell_lattice_constant (
float) – Lattice constant for shell material (optional)
- Return type:
GAM_Atom- Returns:
Core-shell structure
- create_variations(base_structure, size_range, n_structures, **kwargs)[source]
Create multiple variations of a structure.
- Parameters:
base_structure (
str) – Structure typesize_range (
Tuple[float,float]) – (min_size, max_size)n_structures (
int) – Number of structures to generate
- Return type:
List[GAM_Atom]- Returns:
List of structures
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- modify_surface(ligands, coverage=1.0)[source]
Modify surface with ligands.
- Parameters:
atoms – Input structure
ligands (
List[str]) – List of ligand elementscoverage (
float) – Surface coverage (0-1)
- Return type:
GAM_Atom- Returns:
Surface modified structure
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Nanoparticle_Generator(element, size_nm, shape='sphere', doping=None, coating=None, crystal_structure='FCC', **kwargs)[source]
Bases:
objectGeneral-purpose nanoparticle structure generator for atomistic simulations.
The Nanoparticle_Generator class provides a flexible and modular tool for constructing atomic-scale models of nanoparticles with arbitrary geometries, materials, and orientations. It supports the creation of finite clusters, spherical or polyhedral nanoparticles, and core–shell architectures with user-defined crystallography and dimensions.
This class can be used to prepare atomic coordinates for density functional theory (DFT), molecular dynamics (MD), or machine learning (ML) workflows. It is particularly suited for generating input structures for nanomaterials research involving metals, semiconductors, and hybrid systems.
- Supported features include:
Generation of finite nanoparticles with specified radius, shape, and lattice
Core–shell or multi-layered structures
Selection of crystalline structure (FCC, BCC, HCP, etc.)
Randomized orientation and rotation of particles
Atom-based filtering for specific elements or sublattices
Export to standard formats such as XYZ or ASE-compatible structures
- The implementation can be extended to support:
Nanorods, nanowires, and anisotropic morphologies
Surface relaxation or reconstruction
Doping, vacancies, and alloy generation
Integration with LAMMPS, VASP, or ASE simulation interfaces
- Parameters:
element (str) – Chemical symbol of the atomic species (e.g., ‘Au’, ‘Ag’, ‘Si’).
lattice_constant (float) – Lattice constant of the crystal in Ångströms.
structure_type ({'FCC', 'BCC', 'HCP', 'diamond', ...}) – Crystal structure used for atomic packing.
radius (float) – Radius of the nanoparticle in Ångströms.
center (tuple of float, optional) – Cartesian coordinates of the nanoparticle center. Default is (0.0, 0.0, 0.0).
core_element (str, optional) – If specified, the core region of the nanoparticle will use this element.
core_radius (float, optional) – Radius of the core region (Å) when building core–shell particles.
random_orientation (bool, optional) – If True, applies a random rotation to the generated particle. Default is False.
vacuum (float, optional) – Optional vacuum spacing in Ångströms for periodic export. Default is 10.0 Å.
save_path (str, optional) – Path for saving generated structures in .xyz or .cif format.
seed (int, optional) – Random seed for reproducibility.
- atoms
List of atoms with positions, element type, and optional metadata.
- Type:
list of GAM_Atom
- bonds
List of identified bonds (if neighbor detection is used).
- Type:
list of GAM_Bond
- lattice_vectors
Lattice vectors defining the crystal unit cell.
- Type:
numpy.ndarray
- meta
Metadata dictionary containing generation parameters and history.
- Type:
dict
- center
Center of the nanoparticle in Cartesian coordinates.
- Type:
tuple of float
- radius
Radius of the nanoparticle in Ångströms.
- Type:
float
- build() None
Construct the nanoparticle structure from the given parameters.
- generate_core_shell(core_element: str, core_radius: float) None
Create a core–shell nanoparticle by replacing atoms within the core radius.
- apply_rotation(angle: float, axis: str = 'z') None
Rotate the nanoparticle by a given angle around a specified axis.
- translate(dx: float, dy: float, dz: float) None[source]
Translate all atoms by the specified vector.
- nearest_neighbors(r_cut: float | None = None) None
Identify bonds based on a distance cutoff.
- filter_atoms(element: str) list[GAM_Atom]
Return atoms belonging to a specific element.
- get_positions() list[tuple[float, float, float]][source]
Return atomic positions as (x, y, z) tuples.
- get_elements() list[str][source]
Return a list of all atomic species in the nanoparticle.
- to_xyz(path: str) None[source]
Export the nanoparticle to an XYZ file.
- to_ase() ase.Atoms[source]
Convert the nanoparticle to an ASE-compatible Atoms object.
Notes
The atomic cutoff radius for neighbor detection should be set according to the typical bond length of the chosen element (e.g., 1.2× nearest-neighbor distance).
The nanoparticle surface morphology depends on both lattice type and radius.
Randomized orientation can be used to eliminate orientation bias in ML datasets.
Large nanoparticles (>10,000 atoms) may require optimized neighbor-search algorithms.
The class is designed to be modular, allowing integration with simulation workflows such as VASP, Quantum ESPRESSO, LAMMPS, or CP2K.
Examples
>>> # Generate a 5 nm gold nanoparticle >>> from pygamlab import Nanoparticle_Generator >>> npg = Nanoparticle_Generator(element='Au', lattice_constant=4.08, ... structure_type='FCC', radius=25.0) >>> npg.build() >>> npg.to_xyz('Au_nanoparticle.xyz')
>>> # Generate a core–shell Ag@Au nanoparticle >>> cs = Nanoparticle_Generator(element='Au', lattice_constant=4.08, ... structure_type='FCC', radius=30.0) >>> cs.generate_core_shell(core_element='Ag', core_radius=15.0) >>> cs.to_xyz('AgAu_core_shell.xyz')
- add_element(element, percentage, distribution='random')[source]
Add an element to create an alloy nanoparticle.
- Parameters:
element (
str) – Element symbol to add (e.g., ‘Ag’, ‘Cu’)percentage (
float) – Percentage of the new element (0-100)distribution (
str) – Distribution method (‘random’, ‘surface’, ‘core’, ‘layered’)
- Return type:
None
- copy()[source]
Create a deep copy of the structure.
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_composition()[source]
Get the current composition of the nanoparticle as percentages.
- Return type:
Dict[str,float]- Returns:
Dictionary mapping element symbols to their percentages
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_info()[source]
Get comprehensive information about the nanoparticle.
- Return type:
Dict[str,Any]- Returns:
Dictionary containing nanoparticle information
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- save_parameters(file_path)[source]
Save nanoparticle parameters to a JSON file.
- Parameters:
file_path (
str) – Path to save the parameters file- Return type:
None
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Nanotube_Generator(n, m, length=10.0, atom_type='C', custom_atom=None, defects=None, doping=None, strain=None, multi_wall=None, functionalization=None, verbose=False)[source]
Bases:
objectAdvanced chiral nanotube structure generator with extensive customization options.
The Nanotube_Generator class provides a robust and modular framework for constructing single-walled (SWCNT), double-walled (DWCNT), or multi-walled (MWCNT) nanotube structures with arbitrary chirality, composition, and geometry. It is designed for computational materials science applications such as density functional theory (DFT), molecular dynamics (MD), and machine learning (ML) datasets requiring atomically resolved nanotube structures.
This generator supports a wide range of materials beyond carbon, including silicon, germanium, boron nitride (BN), silicon carbide (SiC), transition metal dichalcogenides (MoS₂, WS₂), and III–V compounds such as GaN and InN. It enables detailed control over structural, chemical, and defect configurations to simulate realistic experimental conditions.
Key Features¶
Generation of chiral (n, m) nanotubes with precise geometric parameters
Calculation of diameter, chiral angle, translation vector, and lattice constants
Support for multi-walled nanotubes via concentric wall generation
Introduction of various structural defects (vacancies, Stone–Wales, substitutional)
Doping and alloying with customizable dopant types and concentrations
Application of uniaxial, compressive, or radial strain
Surface functionalization with chemical groups (e.g., –OH, –COOH)
Export to XYZ and ASE-compatible formats
- type n:
int- param n:
Chiral indices defining the nanotube (n, m). Determines the nanotube’s chirality, electronic properties, and geometry.
- type n:
int
- type m:
int- param m:
Chiral indices defining the nanotube (n, m). Determines the nanotube’s chirality, electronic properties, and geometry.
- type m:
int
- type length:
float- param length:
Length of the nanotube in Ångströms.
- type length:
float, default=10.0
- type atom_type:
str- param atom_type:
Atomic species of the nanotube (e.g., ‘C’, ‘BN’, ‘MoS2’).
- type atom_type:
str, default=’C’
- type custom_atom:
Optional[AtomProperties]- param custom_atom:
Custom atom definition, if not included in predefined atom data.
- type custom_atom:
AtomProperties, optional
- type defects:
Optional[Dict]- param defects:
Defect configuration. Example:
{'vacancies': 0.02, 'stone_wales': 0.01, 'substitutions': {'atom': 'B', 'ratio': 0.03}}- type defects:
dict, optional
- type doping:
Optional[Dict]- param doping:
Doping configuration. Example:
{'dopant': 'N', 'concentration': 0.02, 'pattern': 'periodic'}- type doping:
dict, optional
- type strain:
Optional[Dict]- param strain:
Strain parameters defining deformation mode and magnitude. Example:
{'type': 'tensile', 'magnitude': 0.05}- type strain:
dict, optional
- type multi_wall:
Optional[List[Tuple[int,int]]]- param multi_wall:
List of chiral indices defining additional walls for multi-walled nanotubes. Example:
[(10,10), (15,15), (20,20)]- type multi_wall:
list of tuple(int, int), optional
- type functionalization:
Optional[Dict]- param functionalization:
Parameters for surface functionalization. Example:
{'groups': ['COOH', 'OH'], 'density': 0.1}- type functionalization:
dict, optional
- type verbose:
bool- param verbose:
Print detailed generation progress and statistics.
- type verbose:
bool, default=False
- atoms
List of atomic objects representing all atoms in the nanotube.
- Type:
list of GAM_Atom
- bonds
List of interatomic bonds with computed lengths and connectivity.
- Type:
list of GAM_Bond
- meta
Metadata containing nanotube properties, lattice parameters, and configuration.
- Type:
dict
- last_generated
Cached data of the most recently generated nanotube.
- Type:
dict
- generation_stats
Summary statistics such as atom count, bond lengths, and composition.
- Type:
dict
- origin
Origin of the nanotube (x, y) coordinates.
- Type:
tuple of float
- rotation
Cumulative rotation angle applied to the nanotube (in degrees).
- Type:
float
- classify_nanotube(n, m) NanotubeType[source]
Classify the nanotube as zigzag, armchair, or chiral.
- calculate_properties(n, m, bond_length) Dict[str, float][source]
Compute geometric properties including diameter, chiral angle, and unit cell parameters.
- _generate_base_structure(n, m, length, atom_props, sign) Tuple[List, List][source]
Construct the base atomic structure and bonds for a single nanotube wall.
- _generate_bonds(atoms, max_distance) List[Dict][source]
Identify and create bonds between atoms based on cutoff distance.
- _apply_strain(atoms, strain_params) List[Dict][source]
Apply tensile, compressive, or radial strain transformations.
- _introduce_defects(atoms, bonds, defect_params, atom_props) Tuple[List, List][source]
Introduce vacancy, substitutional, or Stone–Wales defects into the structure.
- _apply_doping(atoms, doping_params, atom_props) List[Dict][source]
Substitute atoms with dopants according to given pattern and concentration.
- _create_multi_wall(atoms, bonds, wall_specs, length, base_atom_props) Tuple[List, List][source]
Build multi-walled nanotube structures with appropriate inter-wall spacing.
- _add_functional_groups(atoms, bonds, functionalization) Tuple[List, List][source]
Add surface functional groups to outer atoms.
- _calculate_stats(nanotube_data) Dict[source]
Calculate statistical summaries of the generated structure.
- _print_stats() None[source]
Display generation statistics in human-readable format.
- translate(dx, dy, dz=0.0) None[source]
Translate the nanotube by a specified displacement vector.
- rotate(angle_deg, about_center=True) None[source]
Rotate the nanotube around the z-axis by a given angle.
- copy() List[GAM_Atom][source]
Return a deep copy of the nanotube’s atomic configuration.
- get_atoms() List[GAM_Atom][source]
Return a list of atom objects representing the nanotube.
- get_positions() List[Tuple[float, float, float]][source]
Retrieve all atomic positions.
- get_elements() List[str][source]
Retrieve the list of atomic element symbols.
- to_xyz(filename, nanotube_data=None) None[source]
Export the nanotube structure to XYZ format.
- to_ase() ase.Atoms[source]
Convert the structure to an ASE Atoms object for simulation workflows.
- get_supported_atoms() List[str][source]
Return all supported predefined atomic types.
Notes
Chirality determines the nanotube’s electronic properties: armchair nanotubes (n = m) are metallic, zigzag (m = 0) can be semiconducting or metallic depending on n, and chiral tubes exhibit varying electronic characteristics.
Defects and doping can significantly modify mechanical, optical, and electrical behavior.
Strain and functionalization options are useful for simulating real-world experimental conditions.
The geometry generation algorithm is based on the unrolled graphene lattice method with periodic closure along the chiral vector.
Interlayer spacing for multi-walled nanotubes defaults to 3.4 Å (graphitic spacing).
Examples
>>> # Generate a pristine (10,10) armchair carbon nanotube >>> from pygamlab import Nanotube_Generator >>> cnt = Nanotube_Generator(n=10, m=10, length=20.0, atom_type='C', verbose=True)
>>> # Generate a nitrogen-doped (12,0) zigzag BN nanotube >>> doped_bn = Nanotube_Generator(n=12, m=0, atom_type='BN', ... doping={'dopant': 'N', 'concentration': 0.03, 'pattern': 'random'})
>>> # Create a triple-walled CNT >>> mwcnt = Nanotube_Generator(n=5, m=5, multi_wall=[(5,5), (10,10), (15,15)], length=30.0) >>> mwcnt.to_xyz("multiwalled_CNT.xyz")
- ATOM_DATA = {'AlN': AtomProperties(symbol='AlN', radius=0.85, color=(191, 166, 166), mass=20.491, bond_length=1.89), 'BN': AtomProperties(symbol='BN', radius=0.83, color=(255, 181, 181), mass=12.51, bond_length=1.45), 'C': AtomProperties(symbol='C', radius=0.7, color=(64, 64, 64), mass=12.011, bond_length=1.42), 'GaN': AtomProperties(symbol='GaN', radius=0.87, color=(138, 43, 226), mass=41.865, bond_length=1.94), 'Ge': AtomProperties(symbol='Ge', radius=1.2, color=(102, 143, 143), mass=72.63, bond_length=2.44), 'InN': AtomProperties(symbol='InN', radius=0.92, color=(166, 166, 171), mass=128.825, bond_length=2.15), 'MoS2': AtomProperties(symbol='MoS2', radius=1.3, color=(138, 43, 226), mass=160.07, bond_length=2.38), 'Si': AtomProperties(symbol='Si', radius=1.11, color=(240, 200, 160), mass=28.085, bond_length=2.35), 'SiC': AtomProperties(symbol='SiC', radius=0.91, color=(255, 215, 0), mass=20.048, bond_length=1.89), 'WS2': AtomProperties(symbol='WS2', radius=1.35, color=(255, 215, 0), mass=247.97, bond_length=2.41)}
- calculate_properties(n, m, bond_length)[source]
Calculate geometric properties of the nanotube
- Return type:
Dict[str,float]
- classify_nanotube(n, m)[source]
Classify nanotube type based on (n,m) indices
- Return type:
NanotubeType
- copy()[source]
Create a deep copy of the structure.
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- get_supported_atoms()[source]
Get list of supported atom types
- Return type:
List[str]
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Export structure to ASE Atoms object (if ASE is available).
- Returns:
ASE Atoms object or None if ASE not available
- to_xyz(filename, nanotube_data=None)[source]
Export nanotube to XYZ format
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Phosphorene(lattice_a=3.313, lattice_b=4.376, width=10.0, length=10.0, edge_type='zigzag', rotation=0.0, vacuum=15.0, puckering_height=2.14, origin=(0.0, 0.0))[source]
Bases:
objectClass for constructing and manipulating monolayer phosphorene nanostructures.
This class provides a general framework for generating monolayer black phosphorus (phosphorene) in both periodic and finite geometries. Phosphorene, unlike graphene, exhibits an anisotropic puckered structure and a direction-dependent electronic bandgap, making it essential to correctly handle its orthorhombic lattice and out-of-plane buckling.
The Phosphorene class allows for systematic construction of nanoribbons, flakes, or extended sheets with user-defined edge types, rotation angles, and lattice dimensions. It is designed for integration with atomistic modeling workflows (e.g., DFT, MD, or TB simulations).
- Supported features include:
Generation of finite monolayer flakes or extended sheets
Armchair or zigzag edge terminations
Rotation and translation transformations
Puckering height adjustment for structural realism
Bond generation based on nearest-neighbor distance criteria
Export to XYZ and ASE-compatible structures
- The implementation is easily extendable to:
Multilayer phosphorene and van der Waals heterostructures
Vacancy or substitutional defects
Strained configurations and edge reconstructions
Functionalization or doping studies
- Parameters:
lattice_a (float, optional) – Lattice constant along the armchair direction (Å). Default is 3.313 Å.
lattice_b (float, optional) – Lattice constant along the zigzag direction (Å). Default is 4.376 Å.
width (float, optional) – Width of the generated flake (Å). Default is 10.0 Å.
length (float, optional) – Length of the generated flake (Å). Default is 10.0 Å.
edge_type ({'zigzag', 'armchair'}, optional) – Edge orientation of the flake. Default is ‘zigzag’.
rotation (float, optional) – Rotation angle (in degrees) about the z-axis. Default is 0.0°.
vacuum (float, optional) – Additional spacing in the z-direction for isolated layer simulations (Å). Default is 15.0 Å.
puckering_height (float, optional) – Vertical displacement between upper and lower sublayers in the puckered structure (Å). Default is 2.14 Å.
origin (tuple of float, optional) – (x, y) coordinate shift applied after construction. Default is (0.0, 0.0).
- atoms
List of phosphorus atoms in the structure.
- Type:
list of GAM_Atom
- bonds
List of covalent P–P bonds computed via nearest-neighbor search.
- Type:
list of GAM_Bond
- lattice_vectors
Lattice vectors defining the orthorhombic cell geometry.
- Type:
ndarray of shape (2, 3)
- meta
Metadata dictionary containing structural parameters and statistics.
- Type:
dict
- origin
Current origin of the structure in Cartesian coordinates.
- Type:
tuple of float
- build() None[source]
Construct the phosphorene lattice from the specified parameters.
- nearest_neighbors(r_cut: float | None = None) None[source]
Identify and store P–P bonds using a cutoff-based distance search.
- translate(dx: float, dy: float, dz: float = 0.0) None[source]
Translate all atoms by the given displacement vector.
- rotate(angle_deg: float, about_center: bool = True) None[source]
Rotate the structure around the z-axis.
- copy() list[GAM_Atom][source]
Return a deep copy of the current atomic structure.
- get_atoms() list[GAM_Atom][source]
Retrieve a copy of all atoms in the structure.
- get_positions() list[tuple[float, float, float]][source]
Get all atomic positions as a list of (x, y, z) coordinates.
- get_elements() list[str][source]
Get a list of all element symbols (typically all ‘P’).
- to_xyz(path: str) None[source]
Export the phosphorene structure to an .xyz file.
- to_ase() ase.Atoms[source]
Convert the current structure into an ASE Atoms object for use with simulation packages.
Notes
Phosphorene exhibits a puckered honeycomb lattice with four atoms per unit cell and anisotropic in-plane lattice constants.
The armchair direction corresponds to the short lattice vector (a-axis), and the zigzag direction to the longer one (b-axis).
The default cutoff for nearest neighbors corresponds to approximately 1.6 × the typical P–P bond length (~2.2 Å).
For periodic systems, ensure that the vacuum spacing is sufficiently large to avoid interlayer interactions.
Examples
>>> p = Phosphorene(width=15.0, length=12.0, edge_type='armchair', rotation=10) >>> p.build() >>> p.to_xyz("phosphorene_flake.xyz") >>> ase_atoms = p.to_ase() >>> print(f"Phosphorene flake with {len(ase_atoms)} atoms constructed successfully.")
- build()[source]
Construct the phosphorene structure.
- copy()[source]
Create a deep copy of the structure.
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- nearest_neighbors(r_cut=None)[source]
Determine bonds based on distance cutoff.
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Convert to ASE Atoms object (if ASE is available).
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- class PyGamLab.structures.Silicene(lattice_constant=3.87, width=10.0, length=10.0, edge_type='armchair', rotation=0.0, vacuum=15.0, buckling_height=0.44, origin=(0.0, 0.0))[source]
Bases:
objectClass for constructing and manipulating monolayer silicene nanostructures.
This class provides a flexible generator for 2D silicene sheets and flakes, incorporating its characteristic buckled honeycomb lattice. Silicene, the silicon analogue of graphene, exhibits a low-buckled geometry due to the larger atomic radius of silicon, leading to mixed sp²–sp³ hybridization. Its electronic structure, mechanical flexibility, and tunable bandgap make it a key candidate for post-silicon electronics and 2D semiconductor devices.
The Silicene class supports systematic construction of finite or extended structures with customizable lattice parameters, edge orientations, and buckling amplitude. It also provides methods for geometric transformations and bond detection, making it suitable for atomistic simulations, DFT input generation, and molecular dynamics preprocessing.
- Supported features include:
Finite nanoflake or extended monolayer generation
Armchair or zigzag edge terminations
Buckled atomic geometry (adjustable buckling amplitude)
Rotation and translation transformations
Distance-based bond detection
Export to XYZ and ASE-compatible structures
- The implementation can be extended to:
Multilayer silicene and silicene heterostructures
Defect engineering (vacancies, dopants)
Strain-dependent bandgap analysis
Functionalization or oxidation studies
- Parameters:
lattice_constant (float, optional) – Lattice constant of silicene (Å). Default is 3.87 Å.
width (float, optional) – Width of the structure in the armchair direction (Å). Default is 10.0 Å.
length (float, optional) – Length of the structure in the zigzag direction (Å). Default is 10.0 Å.
edge_type ({'zigzag', 'armchair'}, optional) – Edge orientation of the finite flake. Default is ‘armchair’.
rotation (float, optional) – Rotation angle of the entire structure about the z-axis (degrees). Default is 0.0°.
vacuum (float, optional) – Out-of-plane vacuum spacing for periodic systems (Å). Default is 15.0 Å.
buckling_height (float, optional) – Out-of-plane displacement between A and B sublattices (Å). Default is 0.44 Å.
origin (tuple of float, optional) – (x, y) coordinate shift applied after construction. Default is (0.0, 0.0).
- atoms
List of Si atoms in the structure.
- Type:
list of GAM_Atom
- bonds
List of Si–Si bonds identified using a distance cutoff.
- Type:
list of GAM_Bond
- lattice_vectors
Lattice vectors defining the silicene unit cell geometry.
- Type:
list of numpy.ndarray
- meta
Metadata containing structure parameters and descriptors.
- Type:
dict
- origin
Current origin of the flake in Cartesian coordinates.
- Type:
tuple of float
- build() None[source]
Construct the silicene lattice and populate atom and bond lists.
- nearest_neighbors(r_cut: float | None = None) None[source]
Identify nearest neighbors based on a distance cutoff and store bonds.
- translate(dx: float, dy: float, dz: float = 0.0) None[source]
Translate all atomic coordinates by the specified vector.
- rotate(angle_deg: float, about_center: bool = True) None[source]
Rotate the silicene structure about the z-axis.
- copy() list[GAM_Atom][source]
Return a deep copy of all atoms in the structure.
- get_atoms() list[GAM_Atom][source]
Retrieve a copy of all atomic objects in the structure.
- get_positions() list[tuple[float, float, float]][source]
Return atomic positions as a list of Cartesian coordinates.
- get_elements() list[str][source]
Return the list of element symbols (typically all ‘Si’).
- to_xyz(path: str) None[source]
Export the silicene structure to an .xyz file.
- to_ase() ase.Atoms[source]
Convert the structure to an ASE Atoms object for use in simulation workflows.
Notes
Silicene adopts a buckled honeycomb lattice with two atoms per unit cell.
Typical Si–Si bond length is ~2.28 Å, and the buckling height is ~0.44 Å.
The default cutoff for nearest-neighbor detection corresponds to roughly 1.6× the Si–Si bond length.
The armchair and zigzag directions are rotated by 30° relative to each other, similar to graphene but with buckled atomic planes.
The vacuum spacing should be increased (≥15 Å) when simulating isolated layers to prevent interlayer interactions in periodic boundary conditions.
Examples
>>> s = Silicene(width=15.0, length=12.0, edge_type='zigzag', buckling_height=0.44) >>> s.build() >>> s.to_xyz("silicene_flake.xyz") >>> atoms = s.to_ase() >>> print(f"Silicene structure with {len(atoms)} atoms successfully generated.")
- build()[source]
Construct the silicene flake with buckling.
- Return type:
None
- copy()[source]
Create deep copy of the structure.
- Return type:
Silicene
- get_atoms()[source]
Return a copy of the atoms in this molecule.
- Returns:
A list of atom symbols.
- Return type:
List[str]
- get_elements()[source]
Return list of element symbols in the molecule.
- Return type:
List[str]
- get_positions()[source]
Return positions of all atoms as a list of (x, y, z) tuples.
- Return type:
List[Tuple[float,float,float]]
- nearest_neighbors(r_cut=None)[source]
Build bonds using distance cutoff.
- Parameters:
r_cut (
Optional[float]) – Cutoff radius for bond detection (default: 2.28 * 1.6 Å)- Return type:
None
- rotate(angle_deg, about_center=True)[source]
Rotate structure about z-axis.
- to_ase()[source]
Export to ASE Atoms object if available.
- Return type:
Atoms
- to_xyz(path)[source]
Build (if needed) and save structure directly to XYZ file.
- Return type:
None
- translate(dx, dy, dz=0.0)[source]
Translate all atoms by (dx, dy, dz).
- PyGamLab.structures.export(atoms, fmt, file_path=None, **kwargs)[source]
Export a list of GAM_Atom objects to a file in a specified molecular format.
This is a universal export function supporting multiple formats, including XYZ, CIF, POSCAR (VASP), PDB, LAMMPS, Gaussian, and the custom .pygam format.
- Parameters:
atoms (list[GAM_Atom]) – List of atoms to export.
fmt (str) – Target format for export. Supported values include: ‘xyz’, ‘cif’, ‘poscar’, ‘pdb’, ‘lammps’, ‘gaussian’, ‘gjf’, ‘pygamlab’, ‘pygam’, ‘gamlab’.
file_path (str, optional) – File path to save the output. If None, a default path will be generated based on the chosen format.
**kwargs (dict) – Additional keyword arguments passed to the corresponding format-specific exporter.
- Raises:
ValueError – If an unsupported format is specified.
- Return type:
None