Molecule

A Python implementation of the MolSSI QCSchema Molecule object. There are many definitions of Molecule depending on the domain; this particular Molecule is an immutable 3D Cartesian representation with support for quantum chemistry constructs.

Creation

A Molecule can be created using the normal kwargs fashion as shown below:

>>> mol = qcel.models.Molecule(**{"symbols": ["He"], "geometry": [0, 0, 0]})

In addition, there is the from_data attribute to create a molecule from standard strings:

>>> mol = qcel.models.Molecule.from_data("He 0 0 0")
>>> mol
<    Geometry (in Angstrom), charge = 0.0, multiplicity = 1:

       Center              X                  Y                   Z
    ------------   -----------------  -----------------  -----------------
    He                0.000000000000     0.000000000000     0.000000000000
>

Identifiers

A number of unique identifiers are automatically created for each molecule. Additional implementation such as InChI and SMILES are actively being looked into.

Molecular Hash

A molecule hash is automatically created to allow each molecule to be uniquely identified. The following keys are used to generate the hash:

  • symbols

  • masses (1.e-6 tolerance)

  • molecular_charge (1.e-4 tolerance)

  • molecular_multiplicity

  • real

  • geometry (1.e-8 tolerance)

  • fragments

  • fragment_charges (1.e-4 tolerance)

  • fragment_multiplicities

  • connectivity

Hashes can be acquired from any molecule object and a FractalServer automatically generates canonical hashes when a molecule is added to the database.

>>> mol = qcel.models.Molecule(**{"symbols": ["He", "He"], "geometry": [0, 0, -3, 0, 0, 3]})
>>> mol.get_hash()
'84872f975d19aafa62b188b40fbadaf26a3b1f84'

Molecular Formula

The molecular formula is also available sorted in alphabetical order with title case symbol names. Any symbol with a count of one does not have a number associated with it.

>>> mol.get_molecular_formula()
    'He2'

Fragments

A Molecule with fragments can be created either using the -- separators in the from_data function or by passing explicit fragments in the Molecule constructor:

>>> mol = qcel.models.Molecule.from_data(
>>>       """
>>>       Ne 0.000000 0.000000 0.000000
>>>       --
>>>       Ne 3.100000 0.000000 0.000000
>>>       units au
>>>       """)

>>> mol = qcel.models.Molecule(
>>>       geometry=[0, 0, 0, 3.1, 0, 0],
>>>       symbols=["Ne", "Ne"],
>>>       fragments=[[0], [1]]
>>>       )

Fragments from a molecule containing fragment information can be acquired by:

>>> mol.get_fragment(0)
<    Geometry (in Angstrom), charge = 0.0, multiplicity = 1:

       Center              X                  Y                   Z
    ------------   -----------------  -----------------  -----------------
    Ne                0.000000000000     0.000000000000     0.000000000000
>

Obtaining fragments with ghost atoms is also supported:

>>> mol.get_fragment(0, 1)
<    Geometry (in Angstrom), charge = 0.0, multiplicity = 1:

       Center              X                  Y                   Z
    ------------   -----------------  -----------------  -----------------
    Ne                0.000000000000     0.000000000000     0.000000000000
    Ne      (Gh)      3.100000000572     0.000000000000     0.000000000000
>

Fields

class qcelemental.models.Molecule(orient=False, validate=None, **kwargs)[source]

The physical Cartesian representation of the molecular system.

A QCSchema representation of a Molecule. This model contains data for symbols, geometry, connectivity, charges, fragmentation, etc while also supporting a wide array of I/O and manipulation capabilities.

Molecule objects geometry, masses, and charges are truncated to 8, 6, and 4 decimal places respectively to assist with duplicate detection.

Notes

All arrays are stored flat but must be reshapable into the dimensions in attribute shape, with abbreviations as follows:

  • nat: number of atomic = calcinfo_natom

  • nfr: number of fragments

  • <varies>: irregular dimension not systematically reshapable

Parameters
  • orient (bool) –

  • validate (Optional[bool]) –

  • schema_name (qcelemental.models.molecule.ConstrainedStrValue) –

  • schema_version (int) –

  • validated (bool) –

  • symbols (qcelemental.models.types.Array) –

  • geometry (qcelemental.models.types.Array) –

  • name (Optional[str]) –

  • identifiers (Optional[qcelemental.models.molecule.Identifiers]) –

  • comment (Optional[str]) –

  • molecular_charge (float) –

  • molecular_multiplicity (int) –

  • masses (qcelemental.models.types.Array) –

  • real (qcelemental.models.types.Array) –

  • atom_labels (qcelemental.models.types.Array) –

  • atomic_numbers (qcelemental.models.types.Array) –

  • mass_numbers (qcelemental.models.types.Array) –

  • connectivity (types.ConstrainedListValue[Tuple[qcelemental.models.molecule.NonnegativeInt, qcelemental.models.molecule.NonnegativeInt, qcelemental.models.molecule.BondOrderFloat]]) –

  • fragments (List[qcelemental.models.types.Array]) –

  • fragment_charges (List[float]) –

  • fragment_multiplicities (List[int]) –

  • fix_com (bool) –

  • fix_orientation (bool) –

  • fix_symmetry (Optional[str]) –

  • provenance (qcelemental.models.common_models.Provenance) –

  • id (Optional[Any]) –

  • extras (Dict[str, Any]) –

Return type

None

API

class qcelemental.models.Molecule(orient=False, validate=None, **kwargs)[source]

The physical Cartesian representation of the molecular system.

A QCSchema representation of a Molecule. This model contains data for symbols, geometry, connectivity, charges, fragmentation, etc while also supporting a wide array of I/O and manipulation capabilities.

Molecule objects geometry, masses, and charges are truncated to 8, 6, and 4 decimal places respectively to assist with duplicate detection.

Notes

All arrays are stored flat but must be reshapable into the dimensions in attribute shape, with abbreviations as follows:

  • nat: number of atomic = calcinfo_natom

  • nfr: number of fragments

  • <varies>: irregular dimension not systematically reshapable

Parameters
  • orient (bool) –

  • validate (Optional[bool]) –

  • schema_name (qcelemental.models.molecule.ConstrainedStrValue) –

  • schema_version (int) –

  • validated (bool) –

  • symbols (qcelemental.models.types.Array) –

  • geometry (qcelemental.models.types.Array) –

  • name (Optional[str]) –

  • identifiers (Optional[qcelemental.models.molecule.Identifiers]) –

  • comment (Optional[str]) –

  • molecular_charge (float) –

  • molecular_multiplicity (int) –

  • masses (qcelemental.models.types.Array) –

  • real (qcelemental.models.types.Array) –

  • atom_labels (qcelemental.models.types.Array) –

  • atomic_numbers (qcelemental.models.types.Array) –

  • mass_numbers (qcelemental.models.types.Array) –

  • connectivity (types.ConstrainedListValue[Tuple[qcelemental.models.molecule.NonnegativeInt, qcelemental.models.molecule.NonnegativeInt, qcelemental.models.molecule.BondOrderFloat]]) –

  • fragments (List[qcelemental.models.types.Array]) –

  • fragment_charges (List[float]) –

  • fragment_multiplicities (List[int]) –

  • fix_com (bool) –

  • fix_orientation (bool) –

  • fix_symmetry (Optional[str]) –

  • provenance (qcelemental.models.common_models.Provenance) –

  • id (Optional[Any]) –

  • extras (Dict[str, Any]) –

Return type

None

align(ref_mol, *, do_plot=False, verbose=0, atoms_map=False, run_resorting=False, mols_align=False, run_to_completion=False, uno_cutoff=0.001, run_mirror=False, generic_ghosts=False)[source]

Finds shift, rotation, and atom reordering of concern_mol (self) that best aligns with ref_mol.

Wraps qcelemental.molutil.B787() for qcelemental.models.Molecule. Employs the Kabsch, Hungarian, and Uno algorithms to exhaustively locate the best alignment for non-oriented, non-ordered structures.

Parameters
  • ref_mol (qcelemental.models.Molecule) – Molecule to match.

  • atoms_map (bool) – Whether atom1 of ref_mol corresponds to atom1 of concern_mol, etc. If true, specifying True can save much time.

  • mols_align (Union[bool, float]) – Whether ref_mol and concern_mol have identical geometries (barring orientation or atom mapping) and expected final RMSD = 0. If True, procedure is truncated when RMSD condition met, saving time. If float, RMSD tolerance at which search for alignment stops. If provided, the alignment routine will throw an error if it fails to align the molecule within the specified RMSD tolerance.

  • do_plot (bool) – Pops up a mpl plot showing before, after, and ref geometries.

  • run_to_completion (bool) – Run reorderings to completion (past RMSD = 0) even if unnecessary because mols_align=True. Used to test worst-case timings.

  • run_resorting (bool) – Run the resorting machinery even if unnecessary because atoms_map=True.

  • uno_cutoff (float) – TODO

  • run_mirror (bool) – Run alternate geometries potentially allowing best match to ref_mol from mirror image of concern_mol. Only run if system confirmed to be nonsuperimposable upon mirror reflection.

  • generic_ghosts (bool) – When one or both molecules doesn’t have meaningful element info for ghosts (can happen when harvesting from a printout with a generic ghost symbol), set this to True to place all real=False atoms into the same space for alignment. Only allowed when atoms_map=True.

  • verbose (int) – Print level.

Return type

Tuple[Molecule, Dict[str, Any]]

Returns

  • mol (Molecule)

  • data (Dict[key, Any]) – Molecule is internal geometry of self optimally aligned and atom-ordered to ref_mol. Presently all fragment information is discarded. data[‘rmsd’] is RMSD [A] between ref_mol and the optimally aligned geometry computed. data[‘mill’] is a AlignmentMill with fields (shift, rotation, atommap, mirror) that prescribe the transformation from concern_mol and the optimally aligned geometry.

compare(other)[source]

Compares the current object to the provided object recursively.

Parameters
  • other (Model) – The model to compare to.

  • **kwargs – Additional kwargs to pass to qcelemental.compare_recursive.

Returns

True if the objects match.

Return type

bool

dict(*args, **kwargs)[source]

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

classmethod from_data(data, dtype=None, *, orient=False, validate=None, **kwargs)[source]

Constructs a molecule object from a data structure.

Parameters
  • data (Union[str, Dict[str, Any], ndarray, bytes]) – Data to construct Molecule from

  • dtype (Optional[str]) – How to interpret the data, if not passed attempts to discover this based on input type.

  • orient (bool) – Orientates the molecule to a standard frame or not.

  • validate (Optional[bool]) – Validates the molecule or not.

  • **kwargs – Additional kwargs to pass to the constructors. kwargs take precedence over data.

  • kwargs (Dict[str, Any]) –

Returns

A constructed molecule class.

Return type

Molecule

classmethod from_file(filename, dtype=None, *, orient=False, **kwargs)[source]

Constructs a molecule object from a file.

Parameters
  • filename (str) – The filename to build

  • dtype (Optional[str]) – The type of file to interpret.

  • orient (bool) – Orientates the molecule to a standard frame or not.

  • **kwargs – Any additional keywords to pass to the constructor

Returns

A constructed molecule class.

Return type

Molecule

get_fragment(real, ghost=None, orient=False, group_fragments=True)[source]

Get new Molecule with fragments preserved, dropped, or ghosted.

Parameters
  • real (Union[int, List]) – Fragment index or list of indices (0-indexed) to be real atoms in new Molecule.

  • ghost (Union[int, List, None]) – Fragment index or list of indices (0-indexed) to be ghost atoms (basis fns only) in new Molecule.

  • orient (bool) – Whether or not to align (inertial frame) and phase geometry upon new Molecule instantiation (according to _orient_molecule_internal)?

  • group_fragments (bool) – Whether or not to group real fragments at the start of the atom list and ghost fragments toward the back. Previous to v0.5, this was always effectively True. True is handy for finding duplicate (atom-order-independent) molecules by hash. False preserves fragment order (though collapsing gaps for absent fragments) like Psi4’s extract_subsets. False is handy for gradients where atom order of returned values matters.

Returns

New qcelemental.models.Molecule with self's fragments present, ghosted, or absent.

Return type

Molecule

get_hash()[source]

Returns the hash of the molecule.

get_molecular_formula(order='alphabetical')[source]

Returns the molecular formula for a molecule.

Parameters

order (str, optional) – Sorting order of the formula. Valid choices are “alphabetical” and “hill”.

Returns

The molecular formula.

Return type

str

Examples

>>> methane = qcelemental.models.Molecule('''
... H      0.5288      0.1610      0.9359
... C      0.0000      0.0000      0.0000
... H      0.2051      0.8240     -0.6786
... H      0.3345     -0.9314     -0.4496
... H     -1.0685     -0.0537      0.1921
... ''')
>>> methane.get_molecular_formula()
CH4
>>> hcl = qcelemental.models.Molecule('''
... H      0.0000      0.0000      0.0000
... Cl     0.0000      0.0000      1.2000
... ''')
>>> hcl.get_molecular_formula()
ClH
measure(measurements, *, degrees=True)[source]

Takes a measurement of the moleucle from the indicies provided.

Parameters
  • measurements (Union[List[int], List[List[int]]]) – Either a single list of indices or multiple. Return a distance, angle, or dihedral depending if 2, 3, or 4 indices is provided, respectively. Values are returned in Bohr (distance) or degree.

  • degrees (bool) – Returns degrees by default, radians otherwise.

Returns

Either a value or list of the measured values.

Return type

Union[float, List[float]]

nelectrons(ifr=None)[source]

Number of electrons.

Parameters

ifr (Optional[int]) – If not None, only compute for the ifr-th (0-indexed) fragment.

Returns

nelec – Number of electrons in entire molecule or in fragment.

Return type

int

nuclear_repulsion_energy(ifr=None)[source]

Nuclear repulsion energy.

Parameters

ifr (Optional[int]) – If not None, only compute for the ifr-th (0-indexed) fragment.

Returns

nre – Nuclear repulsion energy in entire molecule or in fragment.

Return type

float

orient_molecule()[source]

Centers the molecule and orients via inertia tensor before returning a new Molecule

pretty_print()[source]

Print the molecule in Angstroms. Same as print_out() only always in Angstroms. (method name in libmints is print_in_angstrom)

scramble(*, do_shift=True, do_rotate=True, do_resort=True, deflection=1.0, do_mirror=False, do_plot=False, do_test=False, run_to_completion=False, run_resorting=False, verbose=0)[source]

Generate a Molecule with random or directed translation, rotation, and atom shuffling. Optionally, check that the aligner returns the opposite transformation.

Parameters
  • ref_mol (qcelemental.models.Molecule) – Molecule to perturb.

  • do_shift (Union[bool, Array, List]) – Whether to generate a random atom shift on interval [-3, 3) in each dimension (True) or leave at current origin. To shift by a specified vector, supply a 3-element list.

  • do_rotate (Union[bool, Array, List[List]]) – Whether to generate a random 3D rotation according to algorithm of Arvo. To rotate by a specified matrix, supply a 9-element list of lists.

  • do_resort (Union[bool, List]) – Whether to shuffle atoms (True) or leave 1st atom 1st, etc. (False). To specify shuffle, supply a nat-element list of indices.

  • deflection (float) – If do_rotate, how random a rotation: 0.0 is no change, 0.1 is small perturbation, 1.0 is completely random.

  • do_mirror (bool) – Whether to construct the mirror image structure by inverting y-axis.

  • do_plot (bool) – Pops up a mpl plot showing before, after, and ref geometries.

  • do_test (bool) – Additionally, run the aligner on the returned Molecule and check that opposite transformations obtained.

  • run_to_completion (bool) – By construction, scrambled systems are fully alignable (final RMSD=0). Even so, True turns off the mechanism to stop when RMSD reaches zero and instead proceed to worst possible time.

  • run_resorting (bool) – Even if atoms not shuffled, test the resorting machinery.

  • verbose (int) – Print level.

Return type

Tuple[Molecule, Dict[str, Any]]

Returns

  • mol (Molecule)

  • data (Dict[key, Any]) – Molecule is scrambled copy of ref_mol (self). data[‘rmsd’] is RMSD [A] between ref_mol and the scrambled geometry. data[‘mill’] is a AlignmentMill with fields (shift, rotation, atommap, mirror) that prescribe the transformation from ref_mol to the returned geometry.

Raises

AssertionError – If do_test=True and aligner sanity check fails for any of the reverse transformations.

show(ngl_kwargs=None)[source]

Creates a 3D representation of a molecule that can be manipulated in Jupyter Notebooks and exported as images (.png).

Parameters

ngl_kwargs (Optional[Dict[str, Any]]) – Addition nglview NGLWidget kwargs

Returns

A nglview view of the molecule

Return type

nglview.NGLWidget

to_file(filename, dtype=None)[source]

Writes the Molecule to a file.

Parameters
  • filename (str) – The filename to write to

  • dtype (Optional[str]) – The type of file to write, attempts to infer dtype from the filename if not provided.

Return type

None

to_string(dtype, units=None, *, atom_format=None, ghost_format=None, width=17, prec=12, return_data=False)[source]

Returns a string that can be used by a variety of programs.

Unclear if this will be removed or renamed to “to_psi4_string” in the future

Suggest psi4 –> psi4frag and psi4 route to to_string

Parameters
  • dtype (str) –

  • units (Optional[str]) –

  • atom_format (Optional[str]) –

  • ghost_format (Optional[str]) –

  • width (int) –

  • prec (int) –

  • return_data (bool) –