Repository navigation
Stabilize cell volumes for highly skew lattice bases #137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
srijan2607
wants to merge
4
commits into
python-periodictable:master
Choose a base branch
from
srijan2607:fix/stable-skew-cell-volume
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
1840b82
Avoid cancellation in skew lattice cell volumes
srijan2607 2bbfd2b
Preserve planar angle boundaries and cell volume numeric range
srijan2607 4cfd75a
Address pre-upstream review for periodictable
srijan2607 0dbbf7d
Fix scalar-constructor typing in cell-volume tests
srijan2607 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
|
||
|
|
||
| @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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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)