Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion periodictable/formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,9 @@ def volume(self, *args, **kw) -> float:

*KeyError* : unknown lattice type

*TypeError* : missing or bad lattice parameters
*TypeError* : missing lattice parameters or incompatible parameter types

*ValueError* : lattice angles give a negative volume radicand

Using the cell volume, mass density can be set with::

Expand Down
44 changes: 37 additions & 7 deletions periodictable/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,24 +70,54 @@ def cell_volume(a=None, b=None, c=None, alpha=None, beta=None, gamma=None) -> fl
Cell volume

:Raises:
*TypeError* : missing or invalid parameters
*TypeError* : missing lattice parameters or incompatible parameter types

*ValueError* : lattice angles give a negative volume radicand

The following formula works for all lattice types:

.. math::

V = a b c \sqrt{1 - \cos^2 \alpha - \cos^2 \beta - \cos^2 \gamma
+ 2 \cos \alpha \cos \beta \cos \gamma}

For numerical stability in highly skew or near-degenerate cells, this is
evaluated in the equivalent factored form, with
$s = (\alpha + \beta + \gamma)/2$:

.. math::

V = 2 a b c \sqrt{\sin s \sin(s-\alpha) \sin(s-\beta) \sin(s-\gamma)}
"""
from math import cos, radians, sqrt
from math import fsum, radians, sin, sqrt
if a is None:
raise TypeError('missing lattice parameters')
if b is None:
b = a
if c is None:
c = a
calpha = cos(radians(alpha)) if alpha is not None else 0
cbeta = cos(radians(beta)) if beta is not None else calpha
cgamma = cos(radians(gamma)) if gamma is not None else calpha
V = a*b*c*sqrt(1 - calpha**2 - cbeta**2 - cgamma**2 + 2*calpha*cbeta*cgamma)
return V
alpha = alpha if alpha is not None else 90
beta = beta if beta is not None else alpha
gamma = gamma if gamma is not None else alpha
# Convert through the existing real-number protocol before unary minus:
# unsigned NumPy scalars would otherwise wrap before fsum sees them.
# Unlike float(), singleton fsum rejects numeric strings.
alpha, beta, gamma = fsum((alpha,)), fsum((beta,)), fsum((gamma,))
# Sum in degrees before conversion so exact planar relationships survive.
# fsum also preserves small signed differences next to these boundaries.
s = fsum((alpha, beta, gamma))/2
# sin(s) = sin(180-s); use the complement near the upper boundary.
if s > 90:
s = fsum((360, -alpha, -beta, -gamma))/2
sa = fsum((beta, gamma, -alpha))/2
sb = fsum((alpha, gamma, -beta))/2
sc = fsum((alpha, beta, -gamma))/2
if alpha == beta == gamma == 90:
# Orthogonal cells have an exact unit angular factor.
angular = 1.0
else:
# Factor the Gram determinant to avoid cancellation for skew cells.
angular = 2*sqrt(sin(radians(s))*sin(radians(sa))
*sin(radians(sb))*sin(radians(sc)))
# Keep the dimensionless factor separate: 2*a can overflow needlessly.
return a*b*c*angular
104 changes: 104 additions & 0 deletions test/test_cell_volume.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Check lattice volumes against independent Cartesian geometry."""
from itertools import permutations
from math import atan2, degrees, dist, inf, nextafter, prod, sqrt

import pytest

from periodictable import formula
from periodictable.util import cell_volume


def _dot(u, v):
return sum(x*y for x, y in zip(u, v))


def _cross(u, v):
return (u[1]*v[2] - u[2]*v[1],
u[2]*v[0] - u[0]*v[2],
u[0]*v[1] - u[1]*v[0])


def _parameters(vectors):
lengths = [dist(v, (0, 0, 0)) for v in vectors]
# atan2 avoids losing the small angles before cell_volume is called.
angles = [degrees(atan2(dist(_cross(u, v), (0, 0, 0)), _dot(u, v)))
for u, v in ((vectors[1], vectors[2]),
(vectors[0], vectors[2]),
(vectors[0], vectors[1]))]
return (*lengths, *angles)


@pytest.mark.parametrize("shear", [0, 10, 100, 1000, 10000, 100000])
@pytest.mark.parametrize("order", list(permutations(range(3))))
def test_sheared_primitive_cell(shear, order):
# Integer shears change the basis, but not the lattice or primitive volume.
basis = [(1, 0, 0), (shear, 1, 0), (shear, 0, 1)]
vectors = [basis[k] for k in order]
expected = abs(_dot(vectors[0], _cross(vectors[1], vectors[2])))
assert expected == 1
parameters = _parameters(vectors)
assert cell_volume(*parameters) == pytest.approx(expected, rel=1e-12)

# Formula.volume converts Ang^3 to cm^3; derived density must not depend
# on which primitive basis was used to describe the same crystal.
crystal = formula("Si")
volume = crystal.volume(*parameters)
assert volume == pytest.approx(expected*1e-24, rel=1e-12, abs=0)
density = crystal.molecular_mass/volume
assert density == pytest.approx(crystal.molecular_mass/1e-24, rel=1e-12)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These three asserts pass on mac M2 with rel=5e-16 (≈2 ULP)


@pytest.mark.parametrize("vectors", [
[(2, 0, 0), (0, 3, 0), (0, 0, 4)],
[(2, 1, 0), (-1, 3, 1), (1, -2, 4)],
[(1, 0, 0), (-10000, 1, 0), (0, 0, 2)],
])
def test_cartesian_volume(vectors):
expected = abs(_dot(vectors[0], _cross(vectors[1], vectors[2])))
assert cell_volume(*_parameters(vectors)) == pytest.approx(expected, rel=1e-10)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first two tests also pass with rel=5e-16, but the third requires rel=1e-12



def test_lattice_parameter_defaults():
assert cell_volume(2) == 8
assert cell_volume(2, 3) == 12
assert cell_volume(2, 3, 4) == prod((2, 3, 4))
# Supplying alpha alone describes equal rhombohedral angles.
assert cell_volume(2, alpha=60) == pytest.approx(8/2**0.5)
assert cell_volume(2, alpha=60, beta=90) == pytest.approx(
cell_volume(2, 2, 2, 60, 90, 60))
with pytest.raises(TypeError, match="missing lattice parameters"):
cell_volume()
with pytest.raises(ValueError):
cell_volume(1, alpha=10, beta=10, gamma=90)


@pytest.mark.parametrize("angles", [
(1, 122, 123), (1, 38, 39), (30, 60, 90),
(120, 120, 120), (90, 90, 180),
])
@pytest.mark.parametrize("order", list(permutations(range(3))))
def test_exact_planar_cell(angles, order):
# Exact degree relationships describe coplanar vectors: volume is zero.
assert cell_volume(1, 1, 1, *(angles[k] for k in order)) == 0


@pytest.mark.parametrize("angles", [
(1, 122, nextafter(123, inf)),
(1, 38, nextafter(39, inf)),
(30, 60, nextafter(90, inf)),
(120, 120, nextafter(120, inf)),
])
@pytest.mark.parametrize("order", list(permutations(range(3))))
def test_just_outside_planar_cell(angles, order):
# Do not hide invalid geometry by clamping small negative determinants.
with pytest.raises(ValueError):
cell_volume(1, 1, 1, *(angles[k] for k in order))


@pytest.mark.parametrize("parameters, expected", [
((1e308, 1e-308, 1), 1),
((1e154, 1e154, 1e-308), 1),
((1e308, 1e-308, 1, 60, 60, 60), 1/sqrt(2)),
])
def test_representable_volume_without_early_overflow(parameters, expected):
assert cell_volume(*parameters) == pytest.approx(expected, rel=1e-15)
114 changes: 114 additions & 0 deletions test/test_cell_volume_orthogonal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""Exact orthogonal invariants and neighboring-angle controls."""
from decimal import Decimal
from itertools import permutations
from math import inf, isclose, nextafter

import numpy as np
import pytest

from periodictable import formula
from periodictable.util import cell_volume


@pytest.mark.parametrize("lengths", list(permutations((2, 3, 4))))
@pytest.mark.parametrize("angles", [(), (90,), (90, 90), (90, 90, 90),
(None, 90, None), (None, None, 90)])
def test_exact_orthogonal_volume(lengths, angles):
assert cell_volume(*lengths, *angles) == 24
assert formula("Si").volume(*lengths, *angles) == 24*1e-24


@pytest.mark.parametrize("args, keywords, expected", [
((2,), {}, 8), ((2, 3), {}, 12),
((2,), {"alpha": 90}, 8),
((2,), {"gamma": 90}, 8),
((2,), {"b": 3, "gamma": 90}, 12),
((2,), {"c": 4, "beta": 90}, 16),
])
def test_exact_scalar_defaults(args, keywords, expected):
assert cell_volume(*args, **keywords) == expected


@pytest.mark.parametrize("angle", [nextafter(90, 0), nextafter(90, inf)])
@pytest.mark.parametrize("index", range(3))
def test_adjacent_right_angle(angle, index):
angles = [90, 90, 90]
angles[index] = angle
# The correction is quadratic in a one-ULP deviation from pi/2.
assert isclose(cell_volume(2, 3, 4, *angles), 24, rel_tol=5e-16)


@pytest.mark.parametrize("scalar", [float, np.float32, np.float64, np.int64])
def test_scalar_types(scalar):
actual = cell_volume(*(scalar(x) for x in (2, 3, 4, 90, 90, 90)))
assert actual == 24
# Do not return an integer merely because all lengths are integers.
assert isinstance(actual, (float, np.floating))


@pytest.mark.parametrize("angles", [
(0, 90, 90), (30, 60, 90), (120, 120, 120), (90, 90, 180),
])
def test_flat_cells(angles):
assert cell_volume(2, 3, 4, *angles) == 0


@pytest.mark.parametrize("angles", [(10, 10, 90)])
def test_invalid_cells(angles):
with pytest.raises(ValueError):
cell_volume(2, 3, 4, *angles)
with pytest.raises(ValueError):
formula("Si").volume(2, 3, 4, *angles)


@pytest.mark.parametrize("args", [(), ("2", 3, 4), (Decimal(2), 3, 4),
(2, 3, 4, "90")])
def test_incompatible_parameters(args):
with pytest.raises(TypeError):
cell_volume(*args)


@pytest.mark.parametrize("lengths", [(1e308, 1e-308, 1),
(1e154, 1e154, 1e-308),
(1e-100, 1e-100, 1e-100),
(1e100, 1e100, 1e100)])
def test_extreme_orthogonal_length_product(lengths):
# Preserve the existing left-to-right product, not a general range redesign.
expected = lengths[0]*lengths[1]*lengths[2]*1.0
assert cell_volume(*lengths) == expected
assert cell_volume(*lengths, 90, 90, 90) == expected


# cos(60) = 1/2 gives Gram determinant 1/2 and V = 12 sqrt(2).
# Mixed cases put each unsigned type in every operand position.
REAL_ANGLE_TYPES: list[type[np.integer]] = [
np.uint8, np.uint16, np.uint32, np.uint64,
np.int8, np.int16, np.int32, np.int64,
]
RealAngleType = type[float] | type[np.integer]
REAL_ANGLE_CASES: list[tuple[RealAngleType, RealAngleType, RealAngleType]] = [
(dtype, dtype, dtype) for dtype in REAL_ANGLE_TYPES
]
REAL_ANGLE_CASES += [(dtype, float, np.int64) for dtype in REAL_ANGLE_TYPES[:4]]
REAL_ANGLE_CASES += [(float, dtype, np.int64) for dtype in REAL_ANGLE_TYPES[:4]]
REAL_ANGLE_CASES += [(float, np.int64, dtype) for dtype in REAL_ANGLE_TYPES[:4]]


@pytest.mark.filterwarnings("error")
@pytest.mark.parametrize("dtypes", REAL_ANGLE_CASES)
def test_real_angle_sixty_analytic(dtypes):
angles = [dtype(60) for dtype in dtypes]
# Decimal square root is independent of the production trig identity.
expected = float(Decimal(12)*Decimal(2).sqrt())
assert cell_volume(2, 3, 4, *angles) == pytest.approx(expected, rel=2e-15)
assert formula("Si").volume(2, 3, 4, *angles) == pytest.approx(
expected*1e-24, rel=2e-15)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests pass with rel=5e-16



@pytest.mark.filterwarnings("error")
@pytest.mark.parametrize("dtypes", REAL_ANGLE_CASES)
def test_real_angle_ninety_no_warnings(dtypes):
angles = [dtype(90) for dtype in dtypes]
assert cell_volume(2, 3, 4, *angles) == 24
assert cell_volume(2, alpha=angles[0]) == 8
assert formula("Si").volume(2, 3, 4, *angles) == 24*1e-24
Loading