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
6 changes: 5 additions & 1 deletion periodictable/formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""

from copy import copy
from math import pi, sqrt
from math import isfinite, pi, sqrt
from typing import cast, Union, Any
from collections.abc import Sequence, Callable

Expand Down Expand Up @@ -94,6 +94,8 @@ def mix_by_weight(*args, **kw) -> "Formula":
def _mix_by_weight_pairs(pairs: list[tuple["Formula", float]]) -> "Formula":
from .formulas import Formula # For running as __main__

if any(not isfinite(q) or q < 0 for _, q in pairs):
raise ValueError("mixture quantities must be finite and non-negative")
# Drop pairs with zero quantity
# Note: must be first statement in order to accept iterators
pairs = [(f, q) for f, q in pairs if q > 0]
Expand Down Expand Up @@ -182,6 +184,8 @@ def mix_by_volume(*args, **kw) -> "Formula":
def _mix_by_volume_pairs(pairs: list[tuple["Formula", float]]) -> "Formula":
from .formulas import Formula # For running as __main__

if any(not isfinite(q) or q < 0 for _, q in pairs):
raise ValueError("mixture quantities must be finite and non-negative")
# Drop pairs with zero quantity
# Note: must be first statement in order to accept iterators
pairs = [(f, q) for f, q in pairs if q > 0]
Expand Down
18 changes: 18 additions & 0 deletions test/test_formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@
from periodictable import formula, mix_by_weight, mix_by_volume
from periodictable.formulas import count_elements, pretty


def test_mixtures_reject_negative_or_nonfinite_quantities():
"""Relative material quantities cannot be negative or non-finite."""
water = formula("H2O", density=1.0)
heavy_water = formula("D2O", density=1.0)
for mixer, items in [
(mix_by_weight, ("H2O", -1, "D2O", 1)),
(mix_by_weight, ("H2O", float("nan"), "D2O", 1)),
(mix_by_volume, (water, -1, heavy_water, 1)),
(mix_by_volume, (water, float("inf"), heavy_water, 1)),
]:
try:
mixer(*items)
except ValueError:
pass
else:
raise AssertionError(f"invalid mixture quantities accepted: {items!r}")

def check_parse_fails(s):
try:
formula(s)
Expand Down