molmass¶
Molecular mass calculations.
Molmass is a Python library, console script, and web application to calculate the molecular mass (average, nominal, and isotopic pure), the elemental composition, and the mass distribution spectrum of a molecule given by its chemical formula, relative element weights, or sequence.
Calculations are based on the isotopic composition of the elements. Mass deficiency due to chemical bonding is not taken into account.
The library includes a database of physicochemical and descriptive properties of the chemical elements.
- Author:
- License:
BSD-3-Clause
- Version:
2026.11.1
- DOI:
Quickstart¶
Install the molmass package and all dependencies from the Python Package Index:
python -m pip install -U "molmass[all]"
See Examples and Documentation for using the programming interface.
Print the console script usage:
python -m molmass --help
Run the web application:
python -m molmass --web
Try the Molecular Mass Calculator online.
Source code and support are available on GitHub.
Requirements¶
This revision was tested with the following requirements and dependencies (other versions may work):
Revisions¶
2026.11.1
Reject empty brackets, for example C() or C1.5 (#24, breaking).
Fix elements_gui rendering issues on Windows and macOS.
2026.10.31
Update atomic weights and isotopic compositions (CIAAW 2024, AME2020).
Update Dalton and particle masses to CODATA 2022.
Reject charges inside brackets, for example [Na+] (#20, breaking).
Reject negative and non-finite mass fractions (#22, breaking).
Reject more invalid formulas and arguments (breaking).
Make Element hashable and compare by identity (breaking).
Compare Formula by Hill notation and support sum (breaking).
Use abundance 1 for specified isotopes in Formula.isotope (breaking).
Fix and improve from_fractions (breaking).
Fix several formula parsing bugs.
Fix Formula.isotope, arithmetic, spectrum, and concentration validation.
Fix isotope, eleconfig, and ionenergy tables in elements.sqlite_script.
Add density_unit argument to ppm conversion methods.
Add Element.mass_uncertainty property.
Fix and improve web and elements_gui applications.
Improve docstrings and examples.
Replace optparse with argparse.
Run web application in http.server instead of Flask or CGI.
2026.8.15
Add HTML application based on Pyodide.
2026.6.9
Add convenience methods for concentration calculations.
Use HTML Living Standard in web application.
Drop support for Python 3.11, support Python 3.15.
2026.1.8
…
Refer to the CHANGES file for older revisions.
Examples¶
Calculate the molecular mass, elemental composition, and mass distribution of a molecule from its chemical formula:
>>> from molmass import Formula
>>> f = Formula('C8H10N4O2') # Caffeine
>>> f
Formula('C8H10N4O2')
>>> f.formula # hill notation
'C8H10N4O2'
>>> f.empirical
'C4H5N2O'
>>> f.mass # average mass
194.1909...
>>> f.nominal_mass # == f.isotope.massnumber
194
>>> f.monoisotopic_mass # == f.isotope.mass
194.0803...
>>> f.atoms
24
>>> f.charge
0
>>> f.composition().dataframe()
Count Relative mass Fraction
Element...
C 8 96.085920 0.494801
H 10 10.079410 0.051905
N 4 56.026812 0.288514
O 2 31.998810 0.164780
>>> f.spectrum(min_intensity=0.01).dataframe()
Relative mass Fraction Intensity % m/z
Mass number...
194 194.080376 0.898828 100.000000 194.080376
195 195.082873 0.092625 10.305100 195.082873
196 196.084968 0.008022 0.892492 196.084968
197 197.087214 0.000500 0.055681 197.087214
Access physicochemical and descriptive properties of the chemical elements:
>>> from molmass import ELEMENTS, Element
>>> e = ELEMENTS['C']
>>> e
Element(
6, 'C', 'Carbon',
group=14, period=2, block='p', series=1,
mass=12.01074, mass_uncertainty=0.001,
eleneg=2.55, eleaffin=1.262118,
covrad=0.77, atmrad=0.91, vdwrad=1.7,
tboil=5100.0, tmelt=3825.0, density=3.51,
eleconfig='[He] 2s2 2p2',
oxistates='4*, 2, -4*',
ionenergy=(
11.2603, 24.383, 47.877, 64.492, 392.077,
489.981,
),
isotopes={
12: Isotope(12.0, 0.9893, 12),
13: Isotope(13.00335483534, 0.0107, 13),
},
)
>>> e.number
6
>>> e.symbol
'C'
>>> e.name
'Carbon'
>>> e.description
'Carbon is a member of group 14 of the periodic table...'
>>> e.eleconfig
'[He] 2s2 2p2'
>>> e.eleconfig_dict
{(1, 's'): 2, (2, 's'): 2, (2, 'p'): 2}
>>> str(ELEMENTS[6])
'Carbon'
>>> len(ELEMENTS)
109
License¶
Copyright (c) 1990-2026, Christoph Gohlke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
molmass module¶
- molmass.__version__¶
Molmass version string.
- class molmass.Composition(items)¶
Bases:
objectElemental composition.
The basic interface is an ordered
dict[symbol, CompositionItem]].- Parameters:
items (Sequence[tuple[str, int, float, float]]) – Symbol, count, mass, and fraction for all elements in formula. Symbols must not be repeated.
Examples
>>> c = Formula('D2O').composition() >>> print(c) Element Count Relative mass Fraction % 2H 2 4.028204 20.1133 O 1 15.999405 79.8867 >>> c['O'] CompositionItem(symbol='O', count=1, mass=15.999405, fraction=0.79...)
- property total: CompositionItem¶
Sums of counts (excluding electrons), masses, and fractions.
>>> Formula('2HO').composition().total CompositionItem(symbol='Total', count=2, mass=18.0135..., fraction=...)
- dataframe()¶
Return composition as pandas DataFrame.
>>> Formula('2HO').composition().dataframe() Count Relative mass Fraction Element... 2H 1 2.014102 0.111811 O 1 15.999405 0.888189
- Return type:
pandas.DataFrame
- asdict()¶
Return dict[symbol, tuple[symbol, count, mass, fraction]].
>>> Formula('2HO').composition().asdict() {'2H': (1, 2.0141..., 0.1118...), 'O': (1, 15.9994..., 0.8881...)}
- Return type:
dict[str, tuple[int, float, float]]
- astuple()¶
Return tuple[tuple[symbol, count, mass, fraction], …].
>>> Formula('2HO').composition().astuple() (('2H', 1, 2.0141..., 0.1118...), ('O', 1, 15.9994..., 0.8881...))
- Return type:
tuple[tuple[str, int, float, float], …]
- keys()¶
Return iterator of symbols.
- Return type:
Iterator[str]
- values()¶
Return iterator of CompositionItems.
- Return type:
Iterator[CompositionItem]
- items()¶
Return iterator of (symbol, CompositionItem) pairs.
- Return type:
Iterator[tuple[str, CompositionItem]]
- class molmass.CompositionItem(symbol, count, mass, fraction)¶
Bases:
objectItem of elemental composition.
- Parameters:
symbol (str)
count (int)
mass (float)
fraction (float)
- symbol: str¶
Chemical symbol of element or electron.
- count: int¶
Number of elements or electrons in composition.
- mass: float¶
Relative mass.
- fraction: float¶
Mass fraction.
- astuple()¶
Return (symbol, count, mass, fraction).
- Return type:
tuple[str, int, float, float]
- class molmass.Element(number, symbol, name, group, period, block, series, mass, eleneg, eleaffin, covrad, atmrad, vdwrad, tboil, tmelt, density, eleconfig, oxistates, ionenergy, isotopes, mass_uncertainty=0.0)¶
Bases:
objectChemical element.
- Parameters:
number (int)
symbol (str)
name (str)
group (int)
period (int)
block (str)
series (int)
mass (float)
eleneg (float)
eleaffin (float)
covrad (float)
atmrad (float)
vdwrad (float)
tboil (float)
tmelt (float)
density (float)
eleconfig (str)
oxistates (str)
ionenergy (tuple[float, ...])
isotopes (dict[int, Isotope])
mass_uncertainty (float)
- number: int¶
Atomic number of protons.
- symbol: str¶
Chemical symbol.
- name: str¶
English name.
- group: int¶
Group in periodic table.
- period: int¶
Period in periodic table.
- block: str¶
Block in periodic table.
- series: int¶
Index to chemical series.
- mass: float¶
Relative atomic mass.
The ratio of the average mass of atoms of the element to 1/12 of the mass of an atom of 12C.
- eleneg: float¶
Electronegativity on Pauling scale.
- eleaffin: float¶
Electron affinity in eV.
- covrad: float¶
Covalent radius in angstrom.
- atmrad: float¶
Atomic radius in angstrom.
- vdwrad: float¶
Van der Waals radius in angstrom.
- tboil: float¶
Boiling temperature in K.
- tmelt: float¶
Melting temperature in K.
- density: float¶
Density at 295K in g/cm3 (solids and liquids) or g/L (gases).
- eleconfig: str¶
Ground state electron configuration.
- oxistates: str¶
Oxidation states.
- ionenergy: tuple[float, ...]¶
Ionization energies in eV.
- isotopes: dict[int, Isotope]¶
Isotopic composition.
Mapping of isotope mass number to relative atomic mass and abundance.
- mass_uncertainty: float = 0.0¶
Uncertainty of relative atomic mass.
The uncertainty of the standard atomic weight or half the width of its interval. Zero if the element has no standard atomic weight.
- property protons: int¶
Number of protons.
- property electrons: int¶
Number of electrons.
- property neutrons: int¶
Number of neutrons in most abundant natural stable isotope.
- property nominalmass: int¶
Mass number of most abundant natural stable isotope.
- property exactmass: float¶
Relative atomic mass calculated from isotopic composition.
- property eleconfig_dict: dict[tuple[int, str], int]¶
electrons.
- Type:
Ground state electron configuration (shell, subshell)
- property eleshells: tuple[int, ...]¶
Number of electrons in shell.
- property description: str¶
Text description of element.
- validate()¶
Check consistency of data. Raise ValueError on failure.
- Return type:
None
- class molmass.Formula(formula='', /, groups=None, *, parse_groups=True, parse_oligos=True, parse_fractions=True, parse_arithmetic=True, allow_empty=True)¶
Bases:
objectChemical formula.
Calculate various properties from formula string, such as hill notation, empirical formula, mass, elemental composition, and mass distribution.
- Parameters:
formula (str) – Chemical formula. May contain only symbols of chemical elements, groups, isotopes, parentheses, numbers, and trailing charge. Some errors are raised during initialization, others only when the formula is parsed on demand during instance attribute access or method calls.
groups (dict[str, str] | None) – Mapping of chemical group name to formula in Hill notation. The default is
GROUPS.parse_groups (bool) – Parse chemical group names. Enabled by default.
parse_oligos (bool) – Parse pure peptide and nucleotide sequences. Enabled by default.
parse_fractions (bool) – Parse list of mass fractions. Enabled by default.
parse_arithmetic (bool) – Parse simple arithmetic operators. Enabled by default.
allow_empty (bool) – Allow empty formulas. If False, raise
FormulaErrorfor empty formulas.
Examples
Elements and counts:
>>> Formula('') Formula('')
>>> Formula('H2O') Formula('H2O')
Isotopes:
>>> Formula('D2O') Formula('[2H]2O')
>>> Formula('[30Si]3O2') Formula('[30Si]3O2')
Ion charges:
>>> Formula('[AsO4]3-') Formula('[AsO4]3-')
>>> Formula('O2-2') Formula('[O2]2-')
Abbreviations of chemical groups:
>>> Formula('EtOH') Formula('(C2H5)OH')
Simple arithmetic:
>>> Formula('(COOH)2') Formula('(COOH)2')
>>> Formula('CuSO4.5H2O') Formula('CuSO4(H2O)5')
Relative element weights:
>>> Formula('O: 0.26, 30Si: 0.74') Formula('O2[30Si]3')
Nucleotide sequences:
>>> Formula('CGCGAATTCGCG') Formula('((C10H12N5O5P)2(C9H12N3O6P)4(C10H12N5O6P)4(C10H13N2O7P)2H2O)')
>>> Formula('dsrna(CCUU)') Formula('((C10H12N5O6P)2(C9H12N3O7P)2...(C9H11N2O8P)2(H2O)2)')
Peptide sequences:
>>> Formula('MDRGEQGLLK') Formula('((C4H5NO3)(C5H7NO3)(C2H3NO)2...(C6H12N4O)H2O)')
>>> Formula('peptide(CPK)') Formula('((C3H5NOS)(C6H12N2O)(C5H7NO)H2O)')
- property formula: str¶
Formula string in Hill notation.
>>> Formula('BrC2H5').formula 'C2H5Br' >>> Formula('[(CH3)3Si2]2NNa').formula 'C6H18NNaSi4'
- property empirical: str¶
Empirical formula in Hill notation.
The empirical formula has the simplest whole number ratio of atoms of each element present in the formula.
>>> Formula('H2O').empirical 'H2O' >>> Formula('C6H12O6').empirical 'CH2O' >>> Formula('[SO4]2_4-').empirical '[O4S]2-'
- property expanded: str¶
Formula string with expanded groups, charges, and sequences.
The input formula parsed by
from_string().>>> Formula('WQ').expanded # peptide sequence '((C5H8N2O2)(C11H10N2O)H2O)'
- property atoms: int¶
Number of atoms.
>>> Formula('CH3COOH').atoms 8
- property charge: int¶
Charge number in units of elementary charge.
>>> Formula('SO4_2-').charge -2
- property gcd: int¶
Greatest common divisor of element counts.
>>> Formula('H2O').gcd 1 >>> Formula('C6H12O6').gcd 6
- property mass: float¶
Average relative molecular mass.
The sum of the relative atomic masses of all atoms and charges in the formula. Equals the molar mass in g/mol, that is, the mass of one mole of substance.
>>> Formula('H').mass 1.007941 >>> Formula('H+').mass 1.007392... >>> Formula('SO4_2-').mass 96.06351... >>> Formula('12C').mass 12.0 >>> Formula('C8H10N4O2').mass 194.1909...
- property monoisotopic_mass: float¶
Mass of isotope composed of most abundant elemental isotopes.
>>> Formula('C8H10N4O2').monoisotopic_mass 194.08037...
- property nominal_mass: int¶
Monoisotopic mass number.
The number of protons and neutrons in the isotope composed of the most abundant elemental isotopes.
>>> Formula('C8H10N4O2').nominal_mass 194
- property mz: float¶
Mass-to-charge ratio.
Using the average relative molecular mass.
>>> Formula('H').mz 1.007941 >>> Formula('SO4_2-').mz 48.03175...
- property isotope: Isotope¶
Isotope composed of most abundant elemental isotopes.
Specified isotopes are considered pure, with an abundance of 1.
>>> Formula('C').isotope.mass 12.0 >>> Formula('13C').isotope Isotope(mass=13.0033..., abundance=1.0, massnumber=13...) >>> Formula('C48H32AgCuO12P2Ru4').isotope Isotope(mass=1439.588..., abundance=0.00205..., massnumber=1440...)
- composition(*, isotopic=True)¶
Return elemental composition.
- Parameters:
isotopic (bool) – List isotopes separately as opposed to part of an element.
- Returns:
Elemental composition.
- Return type:
Examples
>>> print(Formula('[12C][13C]C').composition()) Element Count Relative mass Fraction % C 1 12.010740 32.4491 12C 1 12.000000 32.4201 13C 1 13.003355 35.1308
>>> print(Formula('[12C][13C]C').composition(isotopic=False)) Element Count Relative mass Fraction % C 3 37.014095 100.0000
- spectrum(*, min_fraction=1e-16, min_intensity=None)¶
Return low resolution mass spectrum.
Calculated by combining the mass numbers of the elemental isotopes.
- Parameters:
min_fraction (float) – Minimum fraction for pruning intermediate paths. Prune low-probability paths during combinatorial isotope expansion; does not filter final spectrum entries. Must be in range [0, 1].
min_intensity (float | None) – Minimum intensity percentage for final entries. Remove entries below this threshold, relative to the most abundant peak, from the returned spectrum. When set,
Spectrum.meanwill underestimate the true distribution mean.
- Returns:
Mapping of massnumber to mass, fraction, and intensity.
- Return type:
Examples
>>> print(Formula('D').spectrum()) A Relative mass Fraction % Intensity % 2 2.0141018 100.000000 100.000000
>>> print(Formula('H').spectrum()) A Relative mass Fraction % Intensity % 1 1.0078250 99.988500 100.000000 2 2.0141018 0.011500 0.011501
>>> print(Formula('SO4_2-').spectrum(min_intensity=0.1)) A Relative mass Fraction % Intensity % m/z 96 95.952827 94.070057 100.000000 47.976413 97 96.952996 0.886071 0.941927 48.476498 98 97.949936 4.983307 5.297443 48.974968
- __mul__(number, /)¶
Return formula repeated number times.
>>> Formula('HO-') * 2 Formula('[(HO)2]2-')
- Parameters:
number (int)
- Return type:
- __rmul__(number, /)¶
Return formula repeated number times.
>>> 2 * Formula('H2O') Formula('(H2O)2')
- Parameters:
number (int)
- Return type:
- __add__(other, /)¶
Add this and other formula.
>>> Formula('H2O') + Formula('HO-') Formula('[(H2O)(HO)]-')
- __radd__(other, /)¶
Return formula for
0 + formula, enabling use withsum().>>> sum([Formula('H2O'), Formula('HO-')]) Formula('[(H2O)(HO)]-')
- Parameters:
other (int)
- Return type:
- __sub__(other, /)¶
Subtract elements of other formula.
>>> Formula('H2O') - Formula('O') Formula('H2')
- moles(mass, /, unit='g')¶
Return number of moles from mass.
Use to determine amount of substance in moles given mass. Calculate number of moles as mass / molar mass.
- Parameters:
mass (float) – Mass value.
unit (Literal['g', 'mg', 'μg', 'ug', 'ng', 'kg', 'Da', 'kDa', 'MDa']) – Unit of mass {‘g’, ‘mg’, ‘μg’, ‘ug’, ‘ng’, ‘kg’, ‘Da’, ‘kDa’, ‘MDa’}.
- Returns:
Number of moles.
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.moles(5.844) 0.09999... >>> f.moles(500, 'mg') 0.008555... >>> f.moles(1.0, 'Da') 2.841...e-26
- mass_from_moles(moles, /, unit='g')¶
Return mass from number of moles.
Use to determine mass of a substance given amount in moles. Calculate mass as number of moles * molar mass.
- Parameters:
moles (float) – Number of moles.
unit (Literal['g', 'mg', 'μg', 'ug', 'ng', 'kg', 'Da', 'kDa', 'MDa']) – Desired output unit {‘g’, ‘mg’, ‘μg’, ‘ug’, ‘ng’, ‘kg’, ‘Da’, ‘kDa’, ‘MDa’}.
- Returns:
Mass in specified unit.
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.mass_from_moles(0.1) 5.8442... >>> f.mass_from_moles(0.1, 'mg') 5844.26... >>> f.mass_from_moles(1.0, 'Da') 3.519...e+25
- molarity(mass, volume, *, mass_unit='g', volume_unit='L')¶
Return molarity (mol/L) from mass and volume.
Use to determine concentration of a solution. Calculate molarity as mass / molar mass / volume.
- Parameters:
mass (float) – Mass of solute.
volume (float) – Volume of solution.
mass_unit (Literal['g', 'mg', 'μg', 'ug', 'ng', 'kg', 'Da', 'kDa', 'MDa']) – Unit of mass {‘g’, ‘mg’, ‘μg’, ‘ug’, ‘ng’, ‘kg’, ‘Da’, ‘kDa’, ‘MDa’}.
volume_unit (Literal['L', 'mL', 'μL', 'uL', 'nL', 'dL', 'm3', 'cm3', 'dm3']) – Unit of volume {‘L’, ‘mL’, ‘μL’, ‘uL’, ‘nL’, ‘dL’, ‘m3’, ‘cm3’, ‘dm3’}.
- Returns:
Molarity in mol/L.
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.molarity(5.844, 0.1) 0.9999... >>> f.molarity(292.2, 50, mass_unit='mg', volume_unit='mL') 0.09999...
- mass_for_molarity(molarity, volume, *, mass_unit='g', volume_unit='L')¶
Return mass needed for desired molarity.
Use to prepare solutions of desired concentration. Calculate mass as molarity * volume * molar mass.
- Parameters:
molarity (float) – Target concentration (mol/L).
volume (float) – Volume of solution.
mass_unit (Literal['g', 'mg', 'μg', 'ug', 'ng', 'kg', 'Da', 'kDa', 'MDa']) – Desired output unit {‘g’, ‘mg’, ‘μg’, ‘ug’, ‘ng’, ‘kg’, ‘Da’, ‘kDa’, ‘MDa’}.
volume_unit (Literal['L', 'mL', 'μL', 'uL', 'nL', 'dL', 'm3', 'cm3', 'dm3']) – Unit of volume {‘L’, ‘mL’, ‘μL’, ‘uL’, ‘nL’, ‘dL’, ‘m3’, ‘cm3’, ‘dm3’}.
- Returns:
Mass in specified unit.
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.mass_for_molarity(0.15, 1.0) 8.7664... >>> f.mass_for_molarity(0.15, 250, volume_unit='mL') 2.1916... >>> f.mass_for_molarity(0.15, 0.25, mass_unit='mg') 2191.6...
- ppm_to_molarity(ppm, /, density=1.0, *, density_unit='g/mL')¶
Return molarity from parts per million.
Use to convert concentration in ppm (mg/kg) to molarity (mol/L).
- Parameters:
ppm (float) – Concentration in ppm (mg/kg).
density (float) – Solution density (default 1.0 g/mL for water).
density_unit (Literal['g/mL', 'g/cm3', 'kg/L', 'kg/dm3', 'g/L', 'kg/m3', 'mg/mL']) – Unit of density {‘g/mL’, ‘g/cm3’, ‘kg/L’, ‘kg/dm3’, ‘g/L’, ‘kg/m3’, ‘mg/mL’}.
- Returns:
Molarity in mol/L.
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.ppm_to_molarity(1000) 0.01711... >>> f.ppm_to_molarity(1000, 1.2) 0.02053... >>> f.ppm_to_molarity(1000, 1200, density_unit='kg/m3') 0.02053...
- molarity_to_ppm(molarity, /, density=1.0, *, density_unit='g/mL')¶
Return parts per million from molarity.
Use to convert molarity (mol/L) to concentration in ppm (mg/kg).
- Parameters:
molarity (float) – Concentration in mol/L.
density (float) – Solution density (default 1.0 g/mL for water).
density_unit (Literal['g/mL', 'g/cm3', 'kg/L', 'kg/dm3', 'g/L', 'kg/m3', 'mg/mL']) – Unit of density {‘g/mL’, ‘g/cm3’, ‘kg/L’, ‘kg/dm3’, ‘g/L’, ‘kg/m3’, ‘mg/mL’}.
- Returns:
Concentration in ppm (mg/kg).
- Return type:
float
Examples
>>> f = Formula('NaCl') >>> f.molarity_to_ppm(0.1) 5844.26... >>> f.molarity_to_ppm(0.1, 1.2) 4870.22... >>> f.molarity_to_ppm(0.1, 1200, density_unit='g/L') 4870.22...
- __eq__(other, /)¶
Return whether formulas have same Hill notation.
>>> Formula('HOH') == Formula('H2O') True
- Parameters:
other (object)
- Return type:
bool
- class molmass.FormulaError(message, formula='', position=-1)¶
Bases:
ValueErrorError in chemical formula.
- Parameters:
message (str) – Error message.
formula (str) – Chemical formula in which error occurred.
position (int) – Position in formula where error occurred.
Examples
>>> Formula('abc').formula Traceback (most recent call last): ... molmass.molmass.FormulaError: unexpected character 'a' abc ^
>>> Formula('(H2O)2-H2O').formula Traceback (most recent call last): ... molmass.molmass.FormulaError: subtraction not allowed (H2O)2-H2O ......^
>>> Formula('[11C]').formula Traceback (most recent call last): ... molmass.molmass.FormulaError: unknown isotope '11C' [11C] .^
- position: int¶
Position in formula where error occurred.
- message: str¶
Error message.
- formula: str¶
Formula in which error occurred.
- class molmass.Isotope(mass, abundance, massnumber, charge=0)¶
Bases:
objectIsotope properties.
- Parameters:
mass (float)
abundance (float)
massnumber (int)
charge (int)
- mass: float¶
Monoisotopic mass.
- abundance: float¶
Natural fraction on Earth.
- massnumber: int¶
Number of protons and neutrons.
- charge: int = 0¶
Net charge in units of elementary charge.
- property mz: float¶
Mass-to-charge ratio.
- class molmass.Particle(name, mass, charge)¶
Bases:
objectParticle, e.g., electron, proton, or neutron.
- Parameters:
name (str)
mass (float)
charge (float)
- name: str¶
English name.
- mass: float¶
Relative mass.
The ratio of the mass of the particle to 1/12 of the mass of an 12C atom.
- charge: float¶
Electric charge in coulomb.
- class molmass.Spectrum(spectrum, /, charge=0)¶
Bases:
objectMass distribution.
The basic interface is a sorted
dict[massnumber, SpectrumEntry].- Parameters:
spectrum (dict[int, list[float]]) – Mapping of mass number to relative mass and fraction.
charge (int) – Charge number.
Examples
>>> s = Formula('DH').spectrum() >>> print(s) A Relative mass Fraction % Intensity % 3 3.0219268 99.988500 100.000000 4 4.0282036 0.011500 0.011501 >>> s[4] SpectrumEntry(massnumber=4, mass=4.0282..., fraction=0.000115, ...)
- property peak: SpectrumEntry¶
Most abundant entry.
Raise ValueError if spectrum is empty.
>>> Formula('C8H10N4O2').spectrum().peak.mass 194.0803...
- property mean: float¶
Weighted mean mass of spectrum entries.
Calculated as the sum of each entry’s mass weighted by its fraction. Accurate only for unfiltered spectra (where fractions sum to 1). When the spectrum was created with
min_intensityfiltering, low-abundance entries are excluded and the result is an underestimate of the true distribution mean.>>> Formula('C8H10N4O2').spectrum().mean 194.1909...
- property range: tuple[int, int]¶
Smallest and largest massnumbers.
Raise ValueError if spectrum is empty.
>>> Formula('C8H10N4O2').spectrum().range (194, 205)
- dataframe()¶
Return spectrum as pandas DataFrame.
>>> Formula('SO4_2-').spectrum(min_intensity=0.1).dataframe() Relative mass Fraction Intensity % m/z Mass number... 96 95.952827 0.940701 100.000000 47.976413 97 96.952996 0.008861 0.941927 48.476498 98 97.949936 0.049833 5.297443 48.974968
- Return type:
pandas.DataFrame
- asdict()¶
Return dict[massnumber, tuple[mass, fraction, intensity, mz]].
>>> Formula('DH').spectrum().asdict()[4] (4.0282..., 0.000115, 0.0115..., 4.0282...)
- Return type:
dict[int, tuple[float, float, float, float]]
- astuple()¶
Return tuple[tuple[massnumber, mass, fraction, intensity, mz], …].
>>> Formula('DH').spectrum().astuple()[0] (3, 3.0219..., 0.999885, 100.0, 3.0219...)
- Return type:
tuple[tuple[int, float, float, float, float], …]
- keys()¶
Return iterator of massnumbers.
- Return type:
Iterator[int]
- values()¶
Return iterator of SpectrumEntry objects.
- Return type:
Iterator[SpectrumEntry]
- items()¶
Return iterator of (massnumber, SpectrumEntry) pairs.
- Return type:
Iterator[tuple[int, SpectrumEntry]]
- class molmass.SpectrumEntry(massnumber, mass, fraction, intensity, mz)¶
Bases:
objectEntry of mass distribution spectrum.
- Parameters:
massnumber (int)
mass (float)
fraction (float)
intensity (float)
mz (float)
- massnumber: int¶
Mass number, bin of spectrum.
- mass: float¶
Relative mass.
- fraction: float¶
Mass fraction or abundance.
- intensity: float¶
Fraction normalized by maximum fraction in %.
- mz: float¶
Mass-to-charge ratio.
- astuple()¶
Return attributes (massnumber, mass, fraction, intensity, mz).
- Return type:
tuple[int, float, float, float, float]
- molmass.analyze(formula, /, *, maxatoms=512, min_intensity=1e-4, debug=False)¶
Return analysis of chemical formula as string.
- Parameters:
formula (str) – Chemical formula.
maxatoms (int) – Number of atoms below which to calculate spectrum.
min_intensity (float) – Minimum intensity percentage to include in spectrum.
debug (bool) – Raise exceptions instead of printing error message.
- Return type:
str
Examples
>>> print(analyze('C8H10N4O2', min_intensity=0.01)) Formula: C8H10N4O2 Empirical formula: C4H5N2O Nominal mass: 194 Average mass: 194.19095 Monoisotopic mass: 194.08038 (89.883%) Most abundant mass: 194.08038 (89.883%) Mean of distribution: 194.18604 Number of atoms: 24 Elemental Composition Element Count Relative mass Fraction % C 8 96.08592 49.4801 H 10 10.07941 5.1905 N 4 56.02681 28.8514 O 2 31.99881 16.4780 Mass Distribution A Relative mass Fraction % Intensity % 194 194.08038 89.882781 100.000000 195 195.08287 9.262511 10.305100 196 196.08497 0.802196 0.892492 197 197.08721 0.050048 0.055681
- molmass.dilution(molarity, volume, *, final_molarity=None, final_volume=None)¶
Return dilution parameters using M1V1 = M2V2.
Use to calculate final concentration or volume after dilution. Calculate using the formula M1V1 = M2V2.
Volumes must be in the same unit; the unit does not affect the calculation.
Must provide either final_molarity or final_volume.
- Parameters:
molarity (float) – Initial concentration (M).
volume (float) – Initial volume (any unit).
final_molarity (float | None) – Final concentration.
final_volume (float | None) – Final volume (same unit).
- Returns:
Tuple of (final_molarity, final_volume).
- Return type:
tuple[float, float]
Examples
>>> dilution(1.0, 10, final_volume=100) (0.1, 100) >>> dilution(12.0, 10, final_molarity=1.0) (1.0, 120.0)
- molmass.format_charge(charge, prefix='', /)¶
Return string representation of charge.
- Parameters:
charge (int) – Charge number.
prefix (str) – Character placed in front of charge in case
abs(charge)>1.
- Return type:
str
Examples
>>> format_charge(-2, '_') '_2-' >>> format_charge(1, '_') '+'
- molmass.from_elements(elements, /, *, divisor=1, charge=0, fmt=None)¶
Return formula string in Hill notation from elements dict.
- Parameters:
elements (dict[str, dict[int, int]]) – Number of atoms and isotopes by element. See
Formula._elements().divisor (int) – Number by which to divide element counts and charge.
charge (int) – Charge number.
fmt (tuple[str, str, str, str] | None) – Format strings.
- Return type:
str
Examples
>>> from_elements({'C': {0: 4, 12: 2}}, divisor=2) 'C2[12C]'
>>> from_elements( ... {'C': {0: 4, 12: 2}}, ... divisor=2, ... fmt=( ... '{}', ... '{}<sub>{}</sub>', ... '<sup>{}</sup>{}', ... '<sup>{}</sup>{}<sub>{}</sub>', ... ), ... ) 'C<sub>2</sub><sup>12</sup>C'
- molmass.from_fractions(fractions, /, *, maxcount=10, precision=1e-4, tolerance=None)¶
Return empirical formula from elemental mass fractions.
The result is the simplest whole number ratio of atoms in Hill order.
- Parameters:
fractions (dict[str, float]) – Mapping of element or isotope symbols to relative mass fractions. Fractions need not sum to 1. Fractions of symbols denoting the same element or isotope, for example ‘D’ and ‘[2H]’, are added.
maxcount (int) – Largest multiplier tried to turn atom ratios into integers. Atom counts of individual elements may exceed maxcount.
precision (float) – Accept the smallest multiplier for which the summed deviation of atom counts from integers is below
precision * number of symbols * multiplier.tolerance (float | None) – Maximum deviation of any atom count from an integer. By default, return the best fit regardless of deviation.
- Raises:
FormulaError – Invalid symbol or fraction, or deviation exceeds tolerance.
- Return type:
str
Examples
>>> from_fractions({'H': 0.112, 'O': 0.888}) 'H2O' >>> from_fractions({'D': 0.2, 'O': 0.8}) 'O[2H]2' >>> from_fractions({'H': 8.97, 'C': 59.39, 'O': 31.64}) 'C5H9O2' >>> from_fractions({'O': 0.26, '30Si': 0.74}) 'O2[30Si]3'
- molmass.from_oligo(sequence, dtype='ssdna', /)¶
Return chemical formula for polymer of unmodified (deoxy)nucleotides.
Each strand includes a 5’ monophosphate.
- Parameters:
sequence (str) – DNA or RNA sequence.
dtype (str) – Nucleic acid sequence type. One of ‘ssdna’, ‘dsdna’, ‘ssrna’, or ‘dsrna’.
- Return type:
str
Examples
>>> from_oligo('AC', 'ssdna') '((C10H12N5O5P)(C9H12N3O6P)H2O)'
>>> from_oligo('AU', 'dsrna') '((C10H12N5O6P)2(C9H11N2O8P)2(H2O)2)'
>>> f = Formula(from_oligo('ATC G', 'dsdna')) >>> print(f.formula, f.atoms, f.mass) C78H102N30O50P8 268 2507.60913...
>>> f = Formula(from_oligo('AUC G_2+', 'ssrna')) >>> print(f.formula, f.atoms, f.mass) [C38H49N15O29P4]2+ 135 1303.7744...
- molmass.from_peptide(sequence, /)¶
Return chemical formula for polymer of unmodified amino acids.
- Parameters:
sequence (str) – Peptide sequence.
- Return type:
str
Examples
>>> from_peptide('GG') '((C2H3NO)2H2O)'
>>> f = Formula(from_peptide('GPAVL IMCFY WHKRQ NEDST_2+')) >>> print(f.formula, f.atoms, f.mass) [C107H159N29O30S2]2+ 327 2395.7168...
- molmass.from_sequence(sequence, groups, /)¶
Return sequence as chemical formula.
- Parameters:
sequence (str) – DNA, RNA, or peptide sequence.
groups (dict[str, str]) – Mapping of sequence item to chemical formula in Hill notation. One of
DEOXYNUCLEOTIDES,NUCLEOTIDES, orAMINOACIDS.
- Return type:
str
Examples
>>> from_sequence('GAG', AMINOACIDS) '(C3H5NO)(C2H3NO)2'
- molmass.from_string(formula, /, groups=None, *, parse_groups=True, parse_oligos=True, parse_fractions=True, parse_arithmetic=True)¶
Return formula string from user input string.
- Parameters:
formula (str) – Chemical formula. Supports simple, non-nested arithmetic (+ and *), abbreviations of common chemical groups, peptides, oligos, and mass fractions.
groups (dict[str, str] | None) – Mapping of chemical group name to formula in Hill notation. The default is
GROUPS.parse_groups (bool) – Parse chemical group names.
parse_oligos (bool) – Parse pure peptide and nucleotide sequences.
parse_fractions (bool) – Parse list of mass fractions.
parse_arithmetic (bool) – Parse simple arithmetic operators.
- Returns:
Chemical formula composed only of element and isotope symbols, parentheses, numbers, and trailing ion charges.
- Raises:
FormulaError – Invalid formula.
TypeError – Non-string formula.
- Return type:
str
Examples
>>> from_string('Valohp') '(C5H8NO2)' >>> from_string('Valohp', parse_groups=False) 'Valohp' >>> from_string('HLeu2OH') 'H(C6H11NO)2OH' >>> from_string('O: 0.26, 30Si: 0.74') 'O2[30Si]3' >>> from_string('PhNH2.HCl') '(C6H5)NH2HCl' >>> from_string('PhNH2.HCl', parse_arithmetic=False) '(C6H5)NH2.HCl' >>> from_string('CuSO4.5H2O') 'CuSO4(H2O)5' >>> from_string('CuSO4+5*H2O') 'CuSO4(H2O)5' >>> from_string('5*H2O') '(H2O)5' >>> from_string('O2+12C') # not [12C]O2 'O2(C)12' >>> from_string('ssdna(AC)') '((C10H12N5O5P)(C9H12N3O6P)H2O)' >>> from_string('peptide(GG)') '((C2H3NO)2H2O)' >>> from_string('WQ') '((C5H8N2O2)(C11H10N2O)H2O)' >>> from_string('WQ', parse_oligos=False) 'WQ'
- molmass.hill_sorted(symbols, /)¶
Return iterator over element symbols in order of Hill notation.
- Parameters:
symbols (Iterable[str]) – Element symbols.
- Yields:
Element symbols in order of Hill notation.
- Return type:
Iterator[str]
Examples
>>> tuple(hill_sorted('HCO')) ('C', 'H', 'O')
- molmass.join_charge(formula, charge, separator='', /)¶
Return formula with charge appended.
- Parameters:
formula (str) – Chemical formula without charge.
charge (int) – Charge number.
separator (str) – Character separating formula from charge. One of ‘’ or ‘_’.
- Returns:
Formula with charge != 0 appended. If separator is empty, the formula is wrapped in square brackets.
- Return type:
str
Examples
>>> join_charge('Formula', 0) 'Formula' >>> join_charge('Formula', 1) '[Formula]+' >>> join_charge('Formula', 2) '[Formula]2+' >>> join_charge('Formula', -2, '_') 'Formula_2-'
- molmass.main(argv=None, /)¶
Command line usage main function.
- Parameters:
argv (list[str] | None) – Command line arguments.
- Return type:
int
- molmass.mass_charge_ratio(mass, charge, /)¶
Return mass-to-charge ratio.
- Parameters:
mass (float) – Mass to divide by charge.
charge (int) – Charge number in units of elementary charge.
- Return type:
float
Examples
>>> mass_charge_ratio(1.0, -2) 0.5 >>> mass_charge_ratio(1.0, 0) 1.0 >>> f = Formula('SO4_2-') >>> mass_charge_ratio(f.monoisotopic_mass, f.charge) 47.976...
- molmass.split_charge(formula, /)¶
Return formula stripped from charge, and charge.
- Parameters:
formula (str) – Chemical formula with appended charge.
- Returns:
Chemical formula without charge, and charge number.
- Return type:
tuple[str, int]
Examples
>>> split_charge('Formula') ('Formula', 0) >>> split_charge('Formula+') ('Formula', 1) >>> split_charge('Formula++') ('Formula', 2) >>> split_charge('[Formula]2+') ('Formula', 2) >>> split_charge('Formula_2-') ('Formula', -2) >>> split_charge('Formula-2') ('Formula', -2)
- molmass.DensityUnit¶
alias of
Literal[‘g/mL’, ‘g/cm3’, ‘kg/L’, ‘kg/dm3’, ‘g/L’, ‘kg/m3’, ‘mg/mL’]
- molmass.MassUnit¶
alias of
Literal[‘g’, ‘mg’, ‘μg’, ‘ug’, ‘ng’, ‘kg’, ‘Da’, ‘kDa’, ‘MDa’]
- molmass.VolumeUnit¶
alias of
Literal[‘L’, ‘mL’, ‘μL’, ‘uL’, ‘nL’, ‘dL’, ‘m3’, ‘cm3’, ‘dm3’]
- molmass.AMINOACIDS¶
Mapping of amino acid one-letter codes to Hill notation.
H2O is removed from formulas to represent polymerization.
- molmass.DEOXYNUCLEOTIDES¶
Mapping of Deoxynucleoside monophosphates one-letter codes to Hill notation.
H2O is removed from formulas to represent polymerization.
- molmass.ELECTRON = Particle(name='Electron', mass=0.0005485799090441, charge=-1.602176634e-19)¶
Electron particle.
- molmass.ELEMENTARY_CHARGE¶
Elementary charge in coulombs.
- molmass.ELEMENTS¶
Collection of chemical elements with lookup by number, symbol, and name.
An ordered collection of Element instances with lookup by atomic number (int), chemical symbol (str), or element name (str).
- molmass.GROUPS¶
Mapping of common chemical group names to Hill notation.
- molmass.NEUTRON = Particle(name='Neutron', mass=1.00866491606, charge=0.0)¶
Neutron particle.
- molmass.NUCLEOTIDES¶
Mapping of Nucleoside monophosphate one-letter codes to Hill notation.
H2O is removed from formulas to represent polymerization.
- molmass.POSITRON = Particle(name='Positron', mass=0.0005485799090441, charge=1.602176634e-19)¶
Positron or antielectron particle.
- molmass.PREPROCESSORS¶
Mapping of formula preprocessors.
- molmass.PROTON = Particle(name='Proton', mass=1.0072764665789, charge=1.602176634e-19)¶
Proton particle.
molmass.elements¶
Properties of the chemical elements.
Chemical elements, particles, and isotopes are represented as Python class instances. Physicochemical and descriptive properties are accessible as attributes.
Isotope masses are from AME2020 [1]. Isotopic compositions are from CIAAW [2], or from NIST [3] for elements, for which CIAAW publishes intervals only. Element masses are the CIAAW standard atomic weights. For elements with interval atomic weights, masses are calculated from the isotopic compositions and uncertainties are half the interval widths. For elements without standard atomic weight, masses are those of the listed isotope. Particle masses are CODATA 2022 values [4]. Other properties are from mostly Wikipedia [5].
- class molmass.elements.Element(number, symbol, name, group, period, block, series, mass, eleneg, eleaffin, covrad, atmrad, vdwrad, tboil, tmelt, density, eleconfig, oxistates, ionenergy, isotopes, mass_uncertainty=0.0)¶
Bases:
objectChemical element.
- Parameters:
number (int)
symbol (str)
name (str)
group (int)
period (int)
block (str)
series (int)
mass (float)
eleneg (float)
eleaffin (float)
covrad (float)
atmrad (float)
vdwrad (float)
tboil (float)
tmelt (float)
density (float)
eleconfig (str)
oxistates (str)
ionenergy (tuple[float, ...])
isotopes (dict[int, Isotope])
mass_uncertainty (float)
- number: int¶
Atomic number of protons.
- symbol: str¶
Chemical symbol.
- name: str¶
English name.
- group: int¶
Group in periodic table.
- period: int¶
Period in periodic table.
- block: str¶
Block in periodic table.
- series: int¶
Index to chemical series.
- mass: float¶
Relative atomic mass.
The ratio of the average mass of atoms of the element to 1/12 of the mass of an atom of 12C.
- eleneg: float¶
Electronegativity on Pauling scale.
- eleaffin: float¶
Electron affinity in eV.
- covrad: float¶
Covalent radius in angstrom.
- atmrad: float¶
Atomic radius in angstrom.
- vdwrad: float¶
Van der Waals radius in angstrom.
- tboil: float¶
Boiling temperature in K.
- tmelt: float¶
Melting temperature in K.
- density: float¶
Density at 295K in g/cm3 (solids and liquids) or g/L (gases).
- eleconfig: str¶
Ground state electron configuration.
- oxistates: str¶
Oxidation states.
- ionenergy: tuple[float, ...]¶
Ionization energies in eV.
- isotopes: dict[int, Isotope]¶
Isotopic composition.
Mapping of isotope mass number to relative atomic mass and abundance.
- mass_uncertainty: float = 0.0¶
Uncertainty of relative atomic mass.
The uncertainty of the standard atomic weight or half the width of its interval. Zero if the element has no standard atomic weight.
- property protons: int¶
Number of protons.
- property electrons: int¶
Number of electrons.
- property neutrons: int¶
Number of neutrons in most abundant natural stable isotope.
- property nominalmass: int¶
Mass number of most abundant natural stable isotope.
- property exactmass: float¶
Relative atomic mass calculated from isotopic composition.
- property eleconfig_dict: dict[tuple[int, str], int]¶
electrons.
- Type:
Ground state electron configuration (shell, subshell)
- property eleshells: tuple[int, ...]¶
Number of electrons in shell.
- property description: str¶
Text description of element.
- validate()¶
Check consistency of data. Raise ValueError on failure.
- Return type:
None
- class molmass.elements.Isotope(mass, abundance, massnumber, charge=0)¶
Bases:
objectIsotope properties.
- Parameters:
mass (float)
abundance (float)
massnumber (int)
charge (int)
- mass: float¶
Monoisotopic mass.
- abundance: float¶
Natural fraction on Earth.
- massnumber: int¶
Number of protons and neutrons.
- charge: int = 0¶
Net charge in units of elementary charge.
- property mz: float¶
Mass-to-charge ratio.
- class molmass.elements.Particle(name, mass, charge)¶
Bases:
objectParticle, e.g., electron, proton, or neutron.
- Parameters:
name (str)
mass (float)
charge (float)
- name: str¶
English name.
- mass: float¶
Relative mass.
The ratio of the mass of the particle to 1/12 of the mass of an 12C atom.
- charge: float¶
Electric charge in coulomb.
- molmass.elements.ELECTRON: Particle = Particle(name='Electron', mass=0.0005485799090441, charge=-1.602176634e-19)¶
Electron particle.
- molmass.elements.ELEMENTARY_CHARGE¶
Elementary charge in coulombs.
- molmass.elements.ELEMENTS: Elements¶
Collection of chemical elements with lookup by number, symbol, and name.
An ordered collection of Element instances with lookup by atomic number (int), chemical symbol (str), or element name (str).
Examples
>>> ELEMENTS[6] # by atomic number Element(6, 'C', 'Carbon', ...) >>> ELEMENTS['C'] # by symbol Element(6, 'C', 'Carbon', ...) >>> ELEMENTS['Carbon'] # by name Element(6, 'C', 'Carbon', ...)
- molmass.elements.NEUTRON: Particle = Particle(name='Neutron', mass=1.00866491606, charge=0.0)¶
Neutron particle.
molmass.web¶
Molecular Mass Calculator web application.
Run the web application in a local web server:
python -m molmass.web
The application is run in a local server based on the http.server module, and a web browser is opened.
Do not run the built-in server in a production deployment. Instead, for example, create a Flask app and serve it on a production server:
# app.py
from molmass.web import response
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def root():
return response(request.args, url=request.base_url)
- molmass.web.analyze(formula, /, *, maxatoms=512, min_intensity=1e-4)¶
Return analysis of formula as HTML string.
- Parameters:
formula (str) – Chemical formula of at most
MAXLENGTHcharacters.maxatoms (int) – Number of atoms below which to calculate spectrum.
min_intensity (float) – Minimum intensity to include in spectrum.
- Return type:
str
- molmass.web.groups()¶
Return HTML table of chemical groups.
- Return type:
str
- molmass.web.isotopes()¶
Return HTML table of isotope masses and abundances.
- Return type:
str
- molmass.web.main(*, form=None, url=None, open_browser=True)¶
Run web application in local http.server.
- Parameters:
form (dict[str, str] | None) – Form data to use on first request.
url (str | None) – URL at which the web application is served. The default is ‘http://127.0.0.1:5001/’.
open_browser (bool) – Open url in web browser.
- Return type:
int
- molmass.web.response(form, /, url, template=None, help=None, heads='')¶
Return HTML document from submitted web form.
- Parameters:
form (Any) – Mapping of form fields, for example, Flask
request.args.url (str) – URL of web application.
template (str | None) – HTML page template. The default is
PAGE.help (str | None) – Help text. The default is
HELP.heads (str) – Additional HTML page head sections.
- Return type:
str
- molmass.web.HELP¶