index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
10,745 | bunches.mappings | deposit | Adds 'item' to 'classes' and/or 'instances'.
If 'item' is a class, it is added to 'classes.' If it is an object, it
is added to 'instances' and its class is added to 'classes'.
Args:
item (Union[Type, object]): class or instance to add to the Library
instance.
name (Optional[Hashable]): key to use to store 'item'. If not
passed, a key will be created using the 'get_name' method.
| def deposit(
self,
item: Union[Type[Any], object],
name: Optional[Hashable] = None) -> None:
"""Adds 'item' to 'classes' and/or 'instances'.
If 'item' is a class, it is added to 'classes.' If it is an object, it
is added to 'instances' and its class is added to 'classes'.
Args:
item (Union[Type, object]): class or instance to add to the Library
instance.
name (Optional[Hashable]): key to use to store 'item'. If not
passed, a key will be created using the 'get_name' method.
"""
key = name or utilities.get_name(item = item)
if inspect.isclass(item):
self.classes[key] = item
elif isinstance(item, object):
self.instances[key] = item
self.deposit(item = item.__class__)
else:
raise TypeError(f'item must be a class or a class instance')
return
| (self, item: Union[Type[Any], object], name: Optional[collections.abc.Hashable] = None) -> NoneType |
10,751 | bunches.mappings | remove | Removes an item from 'instances' or 'classes.'
If 'item' is found in 'instances', it will not also be removed from
'classes'.
Args:
item (Hashable): key name of item to remove.
Raises:
KeyError: if 'item' is neither found in 'instances' or 'classes'.
| def remove(self, item: Hashable) -> None:
"""Removes an item from 'instances' or 'classes.'
If 'item' is found in 'instances', it will not also be removed from
'classes'.
Args:
item (Hashable): key name of item to remove.
Raises:
KeyError: if 'item' is neither found in 'instances' or 'classes'.
"""
try:
del self.instances[item]
except KeyError:
try:
del self.classes[item]
except KeyError:
raise KeyError(f'{item} is not found in the Library')
return
| (self, item: collections.abc.Hashable) -> NoneType |
10,755 | bunches.mappings | withdraw | Returns instance or class of first match of 'item' from catalogs.
The method prioritizes the 'instances' catalog over 'classes' and any
passed names in the order they are listed.
Args:
item (Union[Hashable, Sequence[Hashable]]): key name(s) of stored
item(s) sought.
kwargs (Optional[MutableMapping[Hashable, Any]]]): keyword arguments
to pass to a newly created instance or, if the stored item is
already an instance to be manually added as attributes. If not
passed, the found item will be returned unaltered. Defaults to
None.
Raises:
KeyError: if 'item' does not match a key to a stored item in either
'instances' or 'classes'.
Returns:
Union[Type[Any], object]: returns a class or instance if 'kwargs'
are None, depending upon with Catalog the matching item is
found. If 'kwargs' are passed, an instance is always returned.
| def withdraw(
self,
item: Union[Hashable, Sequence[Hashable]],
kwargs: Optional[MutableMapping[Hashable, Any]] = None) -> (
Union[Type[Any], object]):
"""Returns instance or class of first match of 'item' from catalogs.
The method prioritizes the 'instances' catalog over 'classes' and any
passed names in the order they are listed.
Args:
item (Union[Hashable, Sequence[Hashable]]): key name(s) of stored
item(s) sought.
kwargs (Optional[MutableMapping[Hashable, Any]]]): keyword arguments
to pass to a newly created instance or, if the stored item is
already an instance to be manually added as attributes. If not
passed, the found item will be returned unaltered. Defaults to
None.
Raises:
KeyError: if 'item' does not match a key to a stored item in either
'instances' or 'classes'.
Returns:
Union[Type[Any], object]: returns a class or instance if 'kwargs'
are None, depending upon with Catalog the matching item is
found. If 'kwargs' are passed, an instance is always returned.
"""
items = utilities.iterify(item)
item = None
for key in items:
for catalog in ['instances', 'classes']:
try:
item = getattr(self, catalog)[key]
break
except KeyError:
pass
if item is not None:
break
if item is None:
raise KeyError(f'No matching item for {item} was found')
if kwargs is not None:
if 'item' in item.__annotations__.keys() and 'item' not in kwargs:
kwargs[item] = items[0]
if inspect.isclass(item):
item = item(**kwargs)
else:
for key, value in kwargs.items():
setattr(item, key, value)
return item # type: ignore
| (self, item: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable]], kwargs: Optional[collections.abc.MutableMapping[collections.abc.Hashable, Any]] = None) -> Union[Type[Any], object] |
10,756 | bunches.sequences | Listing | Basic bunches list replacement.
A Listing differs from an ordinary python list in ways required by
inheriting from Bunch: 'add' and 'subset' methods, storing data in
'contents', and allowing the '+' operator to join Listings with other lists
and Listings) and in 1 other way.
1) It includes a 'prepend' method for adding one or more items to the
beginning of the stored list.
The 'add' method attempts to extend 'contents' with the item to be added.
If this fails, it appends the item to 'contents'.
Args:
contents (MutableSequence[Any]): items to store in a list. Defaults to
an empty list.
| class Listing(base.Bunch, MutableSequence): # type: ignore
"""Basic bunches list replacement.
A Listing differs from an ordinary python list in ways required by
inheriting from Bunch: 'add' and 'subset' methods, storing data in
'contents', and allowing the '+' operator to join Listings with other lists
and Listings) and in 1 other way.
1) It includes a 'prepend' method for adding one or more items to the
beginning of the stored list.
The 'add' method attempts to extend 'contents' with the item to be added.
If this fails, it appends the item to 'contents'.
Args:
contents (MutableSequence[Any]): items to store in a list. Defaults to
an empty list.
"""
contents: MutableSequence[Any] = dataclasses.field(default_factory = list)
""" Public Methods """
def add(self, item: Union[Any, Sequence[Any]]) -> None:
"""Tries to extend 'contents' with 'item'. Otherwise, it appends.
The method will extend all passed sequences, except str types, which it
will append.
Args:
item (Union[Any, Sequence[Any]]): item(s) to add to the 'contents'
attribute.
"""
if isinstance(item, Sequence) and not isinstance(item, str):
self.contents.extend(item)
else:
self.contents.append(item)
return
def insert(self, index: int, item: Any) -> None:
"""Inserts 'item' at 'index' in 'contents'.
Args:
index (int): index to insert 'item' at.
item (Any): object to be inserted.
"""
self.contents.insert(index, item)
return
def prepend(self, item: Union[Any, Sequence[Any]]) -> None:
"""Prepends 'item' to 'contents'.
If 'item' is a non-str sequence, 'prepend' adds its contents to the
stored list in the order they appear in 'item'.
Args:
item (Union[Any, Sequence[Any]]): item(s) to prepend to the
'contents' attribute.
"""
if isinstance(item, Sequence) and not isinstance(item, str):
for thing in reversed(item):
self.prepend(item = thing)
else:
self.insert(0, item)
return
def subset(
self,
include: Optional[Union[Sequence[Any], Any]] = None,
exclude: Optional[Union[Sequence[Any], Any]] = None) -> Listing:
"""Returns a new instance with a subset of 'contents'.
This method applies 'include' before 'exclude' if both are passed. If
'include' is None, all existing keys will be added before 'exclude' is
applied.
Args:
include (Optional[Union[Sequence[Any], Any]]): item(s) to include in
the new instance. Defaults to None.
exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in
the new instance. Defaults to None.
Raises:
ValueError: if 'include' and 'exclude' are both None.
Returns:
Listing: with only items from 'include' and no items in 'exclude'.
"""
if include is None and exclude is None:
raise ValueError('include or exclude must not be None')
else:
if include is None:
contents = self.contents
else:
include = list(utilities.iterify(item = include))
contents = [i for i in self.contents if i in include]
if exclude is not None:
exclude = list(utilities.iterify(item = exclude))
contents = [i for i in contents if i not in exclude]
new_listing = copy.deepcopy(self)
new_listing.contents = contents
return new_listing
""" Dunder Methods """
def __getitem__(self, index: Any) -> Any:
"""Returns value(s) for 'key' in 'contents'.
Args:
index (Any): index to search for in 'contents'.
Returns:
Any: item stored in 'contents' at key.
"""
return self.contents[index]
def __setitem__(self, index: Any, value: Any) -> None:
"""sets 'key' in 'contents' to 'value'.
Args:
index (Any): index to set 'value' to in 'contents'.
value (Any): value to be set at 'key' in 'contents'.
"""
self.contents[index] = value
return
def __delitem__(self, index: Any) -> None:
"""Deletes item at 'key' index in 'contents'.
Args:
index (Any): index in 'contents' to delete.
"""
del self.contents[index]
return
| (contents: collections.abc.MutableSequence[typing.Any] = <factory>) -> None |
10,759 | bunches.sequences | __delitem__ | Deletes item at 'key' index in 'contents'.
Args:
index (Any): index in 'contents' to delete.
| def __delitem__(self, index: Any) -> None:
"""Deletes item at 'key' index in 'contents'.
Args:
index (Any): index in 'contents' to delete.
"""
del self.contents[index]
return
| (self, index: Any) -> NoneType |
10,761 | bunches.sequences | __getitem__ | Returns value(s) for 'key' in 'contents'.
Args:
index (Any): index to search for in 'contents'.
Returns:
Any: item stored in 'contents' at key.
| def __getitem__(self, index: Any) -> Any:
"""Returns value(s) for 'key' in 'contents'.
Args:
index (Any): index to search for in 'contents'.
Returns:
Any: item stored in 'contents' at key.
"""
return self.contents[index]
| (self, index: Any) -> Any |
10,768 | bunches.sequences | __setitem__ | sets 'key' in 'contents' to 'value'.
Args:
index (Any): index to set 'value' to in 'contents'.
value (Any): value to be set at 'key' in 'contents'.
| def __setitem__(self, index: Any, value: Any) -> None:
"""sets 'key' in 'contents' to 'value'.
Args:
index (Any): index to set 'value' to in 'contents'.
value (Any): value to be set at 'key' in 'contents'.
"""
self.contents[index] = value
return
| (self, index: Any, value: Any) -> NoneType |
10,781 | collections.abc | Mapping | A Mapping is a generic container for associating key/value
pairs.
This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.
| from collections.abc import Mapping
| () |
10,808 | collections.abc | MutableSequence | All the operations on a read-write sequence.
Concrete subclasses must provide __new__ or __init__,
__getitem__, __setitem__, __delitem__, __len__, and insert().
| from collections.abc import MutableSequence
| () |
10,822 | collections.abc | insert | S.insert(index, value) -- insert value before index | null | (self, index, value) |
10,826 | collections.abc | Sequence | All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
| from collections.abc import Sequence
| () |
10,838 | bunches.utilities | get_name | Returns str name representation of 'item'.
Args:
item (Any): item to determine a str name.
default(Optional[str]): default name to return if other methods at name
creation fail.
Returns:
str: a name representation of 'item.'
| def get_name(item: Any, default: Optional[str] = None) -> Optional[str]:
"""Returns str name representation of 'item'.
Args:
item (Any): item to determine a str name.
default(Optional[str]): default name to return if other methods at name
creation fail.
Returns:
str: a name representation of 'item.'
"""
if isinstance(item, str):
return item
elif (
hasattr(item, 'name')
and not inspect.isclass(item)
and isinstance(item.name, str)):
return item.name
else:
try:
return snakify(item.__name__)
except AttributeError:
if item.__class__.__name__ is not None:
return snakify(item.__class__.__name__)
else:
return default
| (item: Any, default: Optional[str] = None) -> Optional[str] |
10,840 | bunches.utilities | iterify | Returns 'item' as an iterable, but does not iterate str types.
Args:
item (Any): item to turn into an iterable
Returns:
Iterable: of 'item'. A str type will be stored as a single item in an
Iterable wrapper.
| def iterify(item: Any) -> Iterable:
"""Returns 'item' as an iterable, but does not iterate str types.
Args:
item (Any): item to turn into an iterable
Returns:
Iterable: of 'item'. A str type will be stored as a single item in an
Iterable wrapper.
"""
if item is None:
return iter(())
elif isinstance(item, (str, bytes)):
return iter([item])
else:
try:
return iter(item)
except TypeError:
return iter((item,))
| (item: Any) -> collections.abc.Iterable |
10,844 | bunches.utilities | snakify | Converts a capitalized str to snake case.
Args:
item (str): str to convert.
Returns:
str: 'item' converted to snake case.
| def snakify(item: str) -> str:
"""Converts a capitalized str to snake case.
Args:
item (str): str to convert.
Returns:
str: 'item' converted to snake case.
"""
item = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', item)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', item).lower()
| (item: str) -> str |
10,846 | burnman.classes.anisotropy | AnisotropicMaterial |
A base class for anisotropic elastic materials. The base class
is initialised with a density and a full isentropic stiffness tensor
in Voigt notation. It can then be interrogated to find the values of
different properties, such as bounds on seismic velocities.
There are also several functions which can be called to calculate
properties along directions oriented with respect to the isentropic
elastic tensor.
See :cite:`Mainprice2011`
and https://docs.materialsproject.org/methodology/elasticity/
for mathematical descriptions of each function.
| class AnisotropicMaterial(Material):
"""
A base class for anisotropic elastic materials. The base class
is initialised with a density and a full isentropic stiffness tensor
in Voigt notation. It can then be interrogated to find the values of
different properties, such as bounds on seismic velocities.
There are also several functions which can be called to calculate
properties along directions oriented with respect to the isentropic
elastic tensor.
See :cite:`Mainprice2011`
and https://docs.materialsproject.org/methodology/elasticity/
for mathematical descriptions of each function.
"""
def __init__(self, rho, cijs):
self._isentropic_stiffness_tensor = cijs
self._rho = rho
assert cijs.shape == (6, 6), "cijs must be in Voigt notation (6x6)"
assert np.allclose(cijs.T, cijs), "stiffness_tensor must be symmetric"
Material.__init__(self)
@material_property
def isentropic_stiffness_tensor(self):
return self._isentropic_stiffness_tensor
@material_property
def full_isentropic_stiffness_tensor(self):
return voigt_notation_to_stiffness_tensor(self.isentropic_stiffness_tensor)
@material_property
def isentropic_compliance_tensor(self):
return np.linalg.inv(self.isentropic_stiffness_tensor)
@material_property
def full_isentropic_compliance_tensor(self):
return voigt_notation_to_compliance_tensor(self.isentropic_compliance_tensor)
@material_property
def density(self):
return self._rho
@material_property
def isentropic_bulk_modulus_voigt(self):
"""
:returns: The Voigt bound on the isentropic bulk modulus [Pa].
:rtype: float
"""
K = (
np.sum(
[
[self.isentropic_stiffness_tensor[i][k] for k in range(3)]
for i in range(3)
]
)
/ 9.0
)
return K
@material_property
def isentropic_bulk_modulus_reuss(self):
"""
:returns: The Reuss bound on the isentropic bulk modulus [Pa].
:rtype: float
"""
beta = np.sum(
[
[self.isentropic_compliance_tensor[i][k] for k in range(3)]
for i in range(3)
]
)
return 1.0 / beta
@material_property
def isentropic_bulk_modulus_vrh(self):
"""
:returns: The Voigt-Reuss-Hill average of the isentropic bulk modulus [Pa].
:rtype: float
"""
return 0.5 * (
self.isentropic_bulk_modulus_voigt + self.isentropic_bulk_modulus_reuss
)
@material_property
def isentropic_shear_modulus_voigt(self):
"""
:returns: The Voigt bound on the isentropic shear modulus [Pa].
:rtype: float
"""
G = (
np.sum([self.isentropic_stiffness_tensor[i][i] for i in [0, 1, 2]])
+ np.sum([self.isentropic_stiffness_tensor[i][i] for i in [3, 4, 5]]) * 3.0
- (
self.isentropic_stiffness_tensor[0][1]
+ self.isentropic_stiffness_tensor[1][2]
+ self.isentropic_stiffness_tensor[2][0]
)
) / 15.0
return G
@material_property
def isentropic_shear_modulus_reuss(self):
"""
:returns: The Reuss bound on the isentropic shear modulus [Pa].
:rtype: float
"""
beta = (
np.sum([self.isentropic_compliance_tensor[i][i] for i in [0, 1, 2]]) * 4.0
+ np.sum([self.isentropic_compliance_tensor[i][i] for i in [3, 4, 5]]) * 3.0
- (
self.isentropic_compliance_tensor[0][1]
+ self.isentropic_compliance_tensor[1][2]
+ self.isentropic_compliance_tensor[2][0]
)
* 4.0
) / 15.0
return 1.0 / beta
@material_property
def isentropic_shear_modulus_vrh(self):
"""
:returns: The Voigt-Reuss-Hill average of the isentropic shear modulus [Pa].
:rtype: float
"""
return 0.5 * (
self.isentropic_shear_modulus_voigt + self.isentropic_shear_modulus_reuss
)
@material_property
def isentropic_universal_elastic_anisotropy(self):
"""
:returns: The universal elastic anisotropy [unitless]
:rtype: float
"""
return (
5.0
* (
self.isentropic_shear_modulus_voigt
/ self.isentropic_shear_modulus_reuss
)
+ (self.isentropic_bulk_modulus_voigt / self.isentropic_bulk_modulus_reuss)
- 6.0
)
@material_property
def isentropic_isotropic_poisson_ratio(self):
"""
:returns: The isotropic Poisson ratio (mu) [unitless].
A metric of the laterial response to loading.
:rtype: float
"""
return (
3.0 * self.isentropic_bulk_modulus_vrh
- 2.0 * self.isentropic_shear_modulus_vrh
) / (
6.0 * self.isentropic_bulk_modulus_vrh
+ 2.0 * self.isentropic_shear_modulus_vrh
)
def christoffel_tensor(self, propagation_direction):
"""
:returns: The Christoffel tensor from an elastic stiffness
tensor and a propagation direction for a seismic wave
relative to the stiffness tensor:
T_ik = C_ijkl n_j n_l.
:rtype: float
"""
propagation_direction = unit_normalize(propagation_direction)
Tik = np.tensordot(
np.tensordot(
self.full_isentropic_stiffness_tensor,
propagation_direction,
axes=([1], [0]),
),
propagation_direction,
axes=([2], [0]),
)
return Tik
def isentropic_linear_compressibility(self, direction):
"""
:returns: The linear isentropic compressibility in a given direction
relative to the stiffness tensor [1/Pa].
:rtype: float
"""
direction = unit_normalize(direction)
Sijkk = np.einsum("ijkk", self.full_isentropic_compliance_tensor)
beta = Sijkk.dot(direction).dot(direction)
return beta
def isentropic_youngs_modulus(self, direction):
"""
:returns: The isentropic Youngs modulus in a given direction
relative to the stiffness tensor [Pa].
:rtype: float
"""
direction = unit_normalize(direction)
Sijkl = self.full_isentropic_compliance_tensor
S = Sijkl.dot(direction).dot(direction).dot(direction).dot(direction)
return 1.0 / S
def isentropic_shear_modulus(self, plane_normal, shear_direction):
"""
:returns: The isentropic shear modulus on a plane in a given
shear direction relative to the stiffness tensor [Pa].
:rtype: float
"""
plane_normal = unit_normalize(plane_normal)
shear_direction = unit_normalize(shear_direction)
assert (
np.abs(plane_normal.dot(shear_direction)) < np.finfo(float).eps
), "plane_normal and shear_direction must be orthogonal"
Sijkl = self.full_isentropic_compliance_tensor
G = (
Sijkl.dot(shear_direction)
.dot(plane_normal)
.dot(shear_direction)
.dot(plane_normal)
)
return 0.25 / G
def isentropic_poissons_ratio(self, axial_direction, lateral_direction):
"""
:returns: The isentropic poisson ratio given loading and response
directions relative to the stiffness tensor [unitless].
:rtype: float
"""
axial_direction = unit_normalize(axial_direction)
lateral_direction = unit_normalize(lateral_direction)
assert (
np.abs(axial_direction.dot(lateral_direction)) < np.finfo(float).eps
), "axial_direction and lateral_direction must be orthogonal"
Sijkl = self.full_isentropic_compliance_tensor
x = axial_direction
y = lateral_direction
nu = -(Sijkl.dot(y).dot(y).dot(x).dot(x) / Sijkl.dot(x).dot(x).dot(x).dot(x))
return nu
def wave_velocities(self, propagation_direction):
"""
:returns: The compressional wave velocity, and two
shear wave velocities in a given propagation direction [m/s].
:rtype: list, containing the wave speeds and directions
of particle motion relative to the stiffness tensor
"""
propagation_direction = unit_normalize(propagation_direction)
Tik = self.christoffel_tensor(propagation_direction)
eigenvalues, eigenvectors = np.linalg.eig(Tik)
idx = eigenvalues.argsort()[::-1]
eigenvalues = np.real(eigenvalues[idx])
eigenvectors = eigenvectors[:, idx]
velocities = np.sqrt(eigenvalues / self.density)
return velocities, eigenvectors
| (rho, cijs) |
10,847 | burnman.classes.anisotropy | __init__ | null | def __init__(self, rho, cijs):
self._isentropic_stiffness_tensor = cijs
self._rho = rho
assert cijs.shape == (6, 6), "cijs must be in Voigt notation (6x6)"
assert np.allclose(cijs.T, cijs), "stiffness_tensor must be symmetric"
Material.__init__(self)
| (self, rho, cijs) |
10,848 | burnman.classes.anisotropy | christoffel_tensor |
:returns: The Christoffel tensor from an elastic stiffness
tensor and a propagation direction for a seismic wave
relative to the stiffness tensor:
T_ik = C_ijkl n_j n_l.
:rtype: float
| def christoffel_tensor(self, propagation_direction):
"""
:returns: The Christoffel tensor from an elastic stiffness
tensor and a propagation direction for a seismic wave
relative to the stiffness tensor:
T_ik = C_ijkl n_j n_l.
:rtype: float
"""
propagation_direction = unit_normalize(propagation_direction)
Tik = np.tensordot(
np.tensordot(
self.full_isentropic_stiffness_tensor,
propagation_direction,
axes=([1], [0]),
),
propagation_direction,
axes=([2], [0]),
)
return Tik
| (self, propagation_direction) |
10,849 | burnman.classes.material | copy | null | def copy(self):
return deepcopy(self)
| (self) |
10,850 | burnman.classes.material | debug_print |
Print a human-readable representation of this Material.
| def debug_print(self, indent=""):
"""
Print a human-readable representation of this Material.
"""
raise NotImplementedError(
"Derived classes need to implement debug_print(). This is '"
+ self.__class__.__name__
+ "'"
)
| (self, indent='') |
10,851 | burnman.classes.material | evaluate |
Returns an array of material properties requested through a list of strings
at given pressure and temperature conditions.
At the end it resets the set_state to the original values.
The user needs to call set_method() before.
:param vars_list: Variables to be returned for given conditions
:type vars_list: list of strings
:param pressures: ndlist or ndarray of float of pressures in [Pa].
:type pressures: :class:`numpy.array`, n-dimensional
:param temperatures: ndlist or ndarray of float of temperatures in [K].
:type temperatures: :class:`numpy.array`, n-dimensional
:returns: Array returning all variables at given pressure/temperature values.
output[i][j] is property vars_list[j] for temperatures[i] and pressures[i].
:rtype: :class:`numpy.array`, n-dimensional
| def evaluate(self, vars_list, pressures, temperatures):
"""
Returns an array of material properties requested through a list of strings
at given pressure and temperature conditions.
At the end it resets the set_state to the original values.
The user needs to call set_method() before.
:param vars_list: Variables to be returned for given conditions
:type vars_list: list of strings
:param pressures: ndlist or ndarray of float of pressures in [Pa].
:type pressures: :class:`numpy.array`, n-dimensional
:param temperatures: ndlist or ndarray of float of temperatures in [K].
:type temperatures: :class:`numpy.array`, n-dimensional
:returns: Array returning all variables at given pressure/temperature values.
output[i][j] is property vars_list[j] for temperatures[i] and pressures[i].
:rtype: :class:`numpy.array`, n-dimensional
"""
old_pressure = self.pressure
old_temperature = self.temperature
pressures = np.array(pressures)
temperatures = np.array(temperatures)
assert pressures.shape == temperatures.shape
output = np.empty((len(vars_list),) + pressures.shape)
for i, p in np.ndenumerate(pressures):
self.set_state(p, temperatures[i])
for j in range(len(vars_list)):
output[(j,) + i] = getattr(self, vars_list[j])
if old_pressure is None or old_temperature is None:
# do not set_state if old values were None. Just reset to None
# manually
self._pressure = self._temperature = None
self.reset()
else:
self.set_state(old_pressure, old_temperature)
return output
| (self, vars_list, pressures, temperatures) |
10,852 | burnman.classes.anisotropy | isentropic_linear_compressibility |
:returns: The linear isentropic compressibility in a given direction
relative to the stiffness tensor [1/Pa].
:rtype: float
| def isentropic_linear_compressibility(self, direction):
"""
:returns: The linear isentropic compressibility in a given direction
relative to the stiffness tensor [1/Pa].
:rtype: float
"""
direction = unit_normalize(direction)
Sijkk = np.einsum("ijkk", self.full_isentropic_compliance_tensor)
beta = Sijkk.dot(direction).dot(direction)
return beta
| (self, direction) |
10,853 | burnman.classes.anisotropy | isentropic_poissons_ratio |
:returns: The isentropic poisson ratio given loading and response
directions relative to the stiffness tensor [unitless].
:rtype: float
| def isentropic_poissons_ratio(self, axial_direction, lateral_direction):
"""
:returns: The isentropic poisson ratio given loading and response
directions relative to the stiffness tensor [unitless].
:rtype: float
"""
axial_direction = unit_normalize(axial_direction)
lateral_direction = unit_normalize(lateral_direction)
assert (
np.abs(axial_direction.dot(lateral_direction)) < np.finfo(float).eps
), "axial_direction and lateral_direction must be orthogonal"
Sijkl = self.full_isentropic_compliance_tensor
x = axial_direction
y = lateral_direction
nu = -(Sijkl.dot(y).dot(y).dot(x).dot(x) / Sijkl.dot(x).dot(x).dot(x).dot(x))
return nu
| (self, axial_direction, lateral_direction) |
10,854 | burnman.classes.anisotropy | isentropic_shear_modulus |
:returns: The isentropic shear modulus on a plane in a given
shear direction relative to the stiffness tensor [Pa].
:rtype: float
| def isentropic_shear_modulus(self, plane_normal, shear_direction):
"""
:returns: The isentropic shear modulus on a plane in a given
shear direction relative to the stiffness tensor [Pa].
:rtype: float
"""
plane_normal = unit_normalize(plane_normal)
shear_direction = unit_normalize(shear_direction)
assert (
np.abs(plane_normal.dot(shear_direction)) < np.finfo(float).eps
), "plane_normal and shear_direction must be orthogonal"
Sijkl = self.full_isentropic_compliance_tensor
G = (
Sijkl.dot(shear_direction)
.dot(plane_normal)
.dot(shear_direction)
.dot(plane_normal)
)
return 0.25 / G
| (self, plane_normal, shear_direction) |
10,855 | burnman.classes.anisotropy | isentropic_youngs_modulus |
:returns: The isentropic Youngs modulus in a given direction
relative to the stiffness tensor [Pa].
:rtype: float
| def isentropic_youngs_modulus(self, direction):
"""
:returns: The isentropic Youngs modulus in a given direction
relative to the stiffness tensor [Pa].
:rtype: float
"""
direction = unit_normalize(direction)
Sijkl = self.full_isentropic_compliance_tensor
S = Sijkl.dot(direction).dot(direction).dot(direction).dot(direction)
return 1.0 / S
| (self, direction) |
10,856 | burnman.classes.material | print_minerals_of_current_state |
Print a human-readable representation of this Material at the current
P, T as a list of minerals.
This requires set_state() has been called before.
| def print_minerals_of_current_state(self):
"""
Print a human-readable representation of this Material at the current
P, T as a list of minerals.
This requires set_state() has been called before.
"""
(minerals, fractions) = self.unroll()
if len(minerals) == 1:
print(minerals[0].to_string())
else:
print("Material %s:" % self.to_string())
for mineral, fraction in zip(minerals, fractions):
print(" %g of phase %s" % (fraction, mineral.to_string()))
| (self) |
10,857 | burnman.classes.material | reset |
Resets all cached material properties.
It is typically not required for the user to call this function.
| def reset(self):
"""
Resets all cached material properties.
It is typically not required for the user to call this function.
"""
self._cached = {}
| (self) |
10,858 | burnman.classes.material | set_method |
Set the averaging method. See :doc:`averaging` for details.
.. note:: Needs to be implemented in derived classes.
| def set_method(self, method):
"""
Set the averaging method. See :doc:`averaging` for details.
.. note:: Needs to be implemented in derived classes.
"""
raise NotImplementedError("need to implement set_method() in derived class!")
| (self, method) |
10,859 | burnman.classes.material | set_state |
Set the material to the given pressure and temperature.
:param pressure: The desired pressure in [Pa].
:type pressure: float
:param temperature: The desired temperature in [K].
:type temperature: float
| def set_state(self, pressure, temperature):
"""
Set the material to the given pressure and temperature.
:param pressure: The desired pressure in [Pa].
:type pressure: float
:param temperature: The desired temperature in [K].
:type temperature: float
"""
if not hasattr(self, "_pressure"):
raise Exception(
"Material.set_state() could not find class member _pressure. "
"Did you forget to call Material.__init__(self) in __init___?"
)
self.reset()
self._pressure = pressure
self._temperature = temperature
| (self, pressure, temperature) |
10,860 | burnman.classes.material | set_state_with_volume |
This function acts similarly to set_state, but takes volume and
temperature as input to find the pressure. In order to ensure
self-consistency, this function does not use any pressure functions
from the material classes, but instead finds the pressure using the
brentq root-finding method.
:param volume: The desired molar volume of the mineral [m^3].
:type volume: float
:param temperature: The desired temperature of the mineral [K].
:type temperature: float
:param pressure_guesses: A list of floats denoting the initial
low and high guesses for bracketing of the pressure [Pa].
These guesses should preferably bound the correct pressure,
but do not need to do so. More importantly,
they should not lie outside the valid region of
the equation of state. Defaults to [5.e9, 10.e9].
:type pressure_guesses: list
| def set_state_with_volume(
self, volume, temperature, pressure_guesses=[0.0e9, 10.0e9]
):
"""
This function acts similarly to set_state, but takes volume and
temperature as input to find the pressure. In order to ensure
self-consistency, this function does not use any pressure functions
from the material classes, but instead finds the pressure using the
brentq root-finding method.
:param volume: The desired molar volume of the mineral [m^3].
:type volume: float
:param temperature: The desired temperature of the mineral [K].
:type temperature: float
:param pressure_guesses: A list of floats denoting the initial
low and high guesses for bracketing of the pressure [Pa].
These guesses should preferably bound the correct pressure,
but do not need to do so. More importantly,
they should not lie outside the valid region of
the equation of state. Defaults to [5.e9, 10.e9].
:type pressure_guesses: list
"""
def _delta_volume(pressure, volume, temperature):
# Try to set the state with this pressure,
# but if the pressure is too low most equations of state
# fail. In this case, treat the molar_volume as infinite
# and brentq will try a larger pressure.
try:
self.set_state(pressure, temperature)
return volume - self.molar_volume
except Exception:
return -np.inf
# we need to have a sign change in [a,b] to find a zero.
args = (volume, temperature)
try:
sol = bracket(_delta_volume, pressure_guesses[0], pressure_guesses[1], args)
except ValueError:
raise Exception(
"Cannot find a pressure, perhaps the volume or starting pressures "
"are outside the range of validity for the equation of state?"
)
pressure = brentq(_delta_volume, sol[0], sol[1], args=args)
self.set_state(pressure, temperature)
| (self, volume, temperature, pressure_guesses=[0.0, 10000000000.0]) |
10,861 | burnman.classes.material | to_string |
Returns a human-readable name of this material.
The default implementation will return the name of the class,
which is a reasonable default.
:returns: A human-readable name of the material.
:rtype: str
| def to_string(self):
"""
Returns a human-readable name of this material.
The default implementation will return the name of the class,
which is a reasonable default.
:returns: A human-readable name of the material.
:rtype: str
"""
return "'" + self.name + "'"
| (self) |
10,862 | burnman.classes.material | unroll |
Unroll this material into a list of :class:`burnman.Mineral` and their molar
fractions. All averaging schemes then operate on this list of minerals.
Note that the return value of this function may depend on the current
state (temperature, pressure).
.. note:: Needs to be implemented in derived classes.
:returns: A list of molar fractions which should sum to 1.0,
and a list of :class:`burnman.Mineral` objects
containing the minerals in the material.
:rtype: tuple
| def unroll(self):
"""
Unroll this material into a list of :class:`burnman.Mineral` and their molar
fractions. All averaging schemes then operate on this list of minerals.
Note that the return value of this function may depend on the current
state (temperature, pressure).
.. note:: Needs to be implemented in derived classes.
:returns: A list of molar fractions which should sum to 1.0,
and a list of :class:`burnman.Mineral` objects
containing the minerals in the material.
:rtype: tuple
"""
raise NotImplementedError("need to implement unroll() in derived class!")
| (self) |
10,863 | burnman.classes.anisotropy | wave_velocities |
:returns: The compressional wave velocity, and two
shear wave velocities in a given propagation direction [m/s].
:rtype: list, containing the wave speeds and directions
of particle motion relative to the stiffness tensor
| def wave_velocities(self, propagation_direction):
"""
:returns: The compressional wave velocity, and two
shear wave velocities in a given propagation direction [m/s].
:rtype: list, containing the wave speeds and directions
of particle motion relative to the stiffness tensor
"""
propagation_direction = unit_normalize(propagation_direction)
Tik = self.christoffel_tensor(propagation_direction)
eigenvalues, eigenvectors = np.linalg.eig(Tik)
idx = eigenvalues.argsort()[::-1]
eigenvalues = np.real(eigenvalues[idx])
eigenvectors = eigenvectors[:, idx]
velocities = np.sqrt(eigenvalues / self.density)
return velocities, eigenvectors
| (self, propagation_direction) |
10,864 | burnman.classes.anisotropicmineral | AnisotropicMineral |
A class implementing the anisotropic mineral equation of state described
in :cite:`Myhill2022`.
This class is derived from both Mineral and AnisotropicMaterial,
and inherits most of the methods from these classes.
Instantiation of an AnisotropicMineral takes three required arguments;
a reference Mineral (i.e. a standard isotropic mineral which provides
volume as a function of pressure and temperature), cell_parameters,
which give the lengths of the molar cell vectors and the angles between
them (see :func:`~burnman.utils.unitcell.cell_parameters_to_vectors`),
and an anisotropic parameters object, which should be either a
4D array of anisotropic parameters or a dictionary of parameters which
describe the anisotropic behaviour of the mineral.
For a description of the physical meaning of the parameters in the
4D array, please refer to the code
or to the original paper.
If the user chooses to define their parameters as a dictionary,
they must also provide a function to the psi_function argument
that describes how to compute the tensors Psi, dPsidf and dPsidPth
(in Voigt form). The function arguments should be f, Pth and params,
in that order. The output variables Psi, dPsidf and dPsidth
must be returned in that order in a tuple. The user should
also explicitly state whether the material is orthotropic or not
by supplying a boolean to the orthotropic argument.
States of the mineral can only be queried after setting the
pressure and temperature using set_state().
This class is available as ``burnman.AnisotropicMineral``.
All the material parameters are expected to be in plain SI units. This
means that the elastic moduli should be in Pascals and NOT Gigapascals.
Additionally, the cell parameters should be in m/(mol formula unit)
and not in unit cell lengths. To convert unit cell lengths given in
Angstrom to molar cell parameters you should multiply by 10^(-10) *
(N_a / Z)^1/3, where N_a is Avogadro's number
and Z is the number of formula units per unit cell.
You can look up Z in many places, including www.mindat.org.
Finally, it is assumed that the unit cell of the anisotropic material
is aligned in a particular way relative to the coordinate axes
(the anisotropic_parameters are defined relative to the coordinate axes).
The crystallographic a-axis is assumed to be parallel to the first
spatial coordinate axis, and the crystallographic b-axis is assumed to
be perpendicular to the third spatial coordinate axis.
| class AnisotropicMineral(Mineral, AnisotropicMaterial):
"""
A class implementing the anisotropic mineral equation of state described
in :cite:`Myhill2022`.
This class is derived from both Mineral and AnisotropicMaterial,
and inherits most of the methods from these classes.
Instantiation of an AnisotropicMineral takes three required arguments;
a reference Mineral (i.e. a standard isotropic mineral which provides
volume as a function of pressure and temperature), cell_parameters,
which give the lengths of the molar cell vectors and the angles between
them (see :func:`~burnman.utils.unitcell.cell_parameters_to_vectors`),
and an anisotropic parameters object, which should be either a
4D array of anisotropic parameters or a dictionary of parameters which
describe the anisotropic behaviour of the mineral.
For a description of the physical meaning of the parameters in the
4D array, please refer to the code
or to the original paper.
If the user chooses to define their parameters as a dictionary,
they must also provide a function to the psi_function argument
that describes how to compute the tensors Psi, dPsidf and dPsidPth
(in Voigt form). The function arguments should be f, Pth and params,
in that order. The output variables Psi, dPsidf and dPsidth
must be returned in that order in a tuple. The user should
also explicitly state whether the material is orthotropic or not
by supplying a boolean to the orthotropic argument.
States of the mineral can only be queried after setting the
pressure and temperature using set_state().
This class is available as ``burnman.AnisotropicMineral``.
All the material parameters are expected to be in plain SI units. This
means that the elastic moduli should be in Pascals and NOT Gigapascals.
Additionally, the cell parameters should be in m/(mol formula unit)
and not in unit cell lengths. To convert unit cell lengths given in
Angstrom to molar cell parameters you should multiply by 10^(-10) *
(N_a / Z)^1/3, where N_a is Avogadro's number
and Z is the number of formula units per unit cell.
You can look up Z in many places, including www.mindat.org.
Finally, it is assumed that the unit cell of the anisotropic material
is aligned in a particular way relative to the coordinate axes
(the anisotropic_parameters are defined relative to the coordinate axes).
The crystallographic a-axis is assumed to be parallel to the first
spatial coordinate axis, and the crystallographic b-axis is assumed to
be perpendicular to the third spatial coordinate axis.
"""
def __init__(
self,
isotropic_mineral,
cell_parameters,
anisotropic_parameters,
psi_function=None,
orthotropic=None,
):
if psi_function is None:
self.check_standard_parameters(anisotropic_parameters)
self.anisotropic_params = {"c": anisotropic_parameters}
self.psi_function = self.standard_psi_function
else:
if not isinstance(orthotropic, bool):
raise Exception(
"If the Psi function is provided, "
"you must specify whether your material is "
"orthotropic as a boolean."
)
self.orthotropic = orthotropic
self.anisotropic_params = anisotropic_parameters
self.psi_function = psi_function
self.cell_vectors_0 = cell_parameters_to_vectors(cell_parameters)
if (
np.abs(np.linalg.det(self.cell_vectors_0) - isotropic_mineral.params["V_0"])
> np.finfo(float).eps
):
factor = np.cbrt(
isotropic_mineral.params["V_0"] / np.linalg.det(self.cell_vectors_0)
)
raise Exception(
"The standard state unit vectors are inconsistent "
"with the volume. Suggest multiplying each "
f"by {factor}."
)
# Note, Psi_0 may be asymmetric, in which case the Voigt contraction
# cannot be applied
self.Psi_0 = np.einsum("ij, kl", logm(self.cell_vectors_0), np.eye(3) / 3.0)
self.isotropic_mineral = isotropic_mineral
if "name" in isotropic_mineral.params:
self.name = isotropic_mineral.params["name"]
Mineral.__init__(
self, isotropic_mineral.params, isotropic_mineral.property_modifiers
)
def standard_psi_function(self, f, Pth, params):
# Compute Psi, dPsidPth, dPsidf, needed by most anisotropic properties
c = params["c"]
ns = np.arange(c.shape[-1])
x = c[:, :, 0, :] + c[:, :, 1, :] * f
dPsidf = c[:, :, 1, :]
for i in list(range(2, c.shape[2])):
# non-intuitively, the += operator doesn't simply add in-place,
# so here we overwrite the arrays with new ones
x = x + c[:, :, i, :] * np.power(f, float(i)) / float(i)
dPsidf = dPsidf + c[:, :, i, :] * np.power(f, float(i) - 1.0)
Psi = np.einsum("ikn, n->ik", x, np.power(Pth, ns))
dPsidPth = np.einsum(
"ikn, n->ik", x[:, :, 1:], ns[1:] * np.power(Pth, ns[1:] - 1)
)
dPsidf = np.einsum("ikn, n->ik", dPsidf, np.power(Pth, ns))
return (Psi, dPsidf, dPsidPth)
@copy_documentation(Material.set_state)
def set_state(self, pressure, temperature):
# 1) Compute dPthdf|T
# relatively large dP needed for accurate estimate of dPthdf
self.isotropic_mineral.set_state(pressure, temperature)
V2 = self.isotropic_mineral.V
KT2 = self.isotropic_mineral.K_T
self.isotropic_mineral.set_state_with_volume(V2, self.params["T_0"])
P1 = self.isotropic_mineral.pressure
KT1 = self.isotropic_mineral.K_T
self.dPthdf = KT1 - KT2
self.Pth = pressure - P1
self.isotropic_mineral.set_state(pressure, temperature)
Mineral.set_state(self, pressure, temperature)
# 2) Compute other properties needed for anisotropic equation of state
V = self.V
V_0 = self.params["V_0"]
Vrel = V / V_0
f = np.log(Vrel)
self._Vrel = Vrel
self._f = f
out = self.psi_function(f, self.Pth, self.anisotropic_params)
Psi_Voigt, self.dPsidf_Voigt, self.dPsidPth_Voigt = out
self.Psi = voigt_notation_to_compliance_tensor(Psi_Voigt) + self.Psi_0
# Convert to (f, T) variables
self.dPsidP_Voigt = -self.isothermal_compressibility_reuss * (
self.dPsidf_Voigt + self.dPsidPth_Voigt * self.dPthdf
)
self.dPsidT_Voigt = self.alpha * (
self.dPsidf_Voigt
+ self.dPsidPth_Voigt * (self.dPthdf + self.isothermal_bulk_modulus_reuss)
)
@material_property
def deformation_gradient_tensor(self):
"""
:returns: The deformation gradient tensor describing the deformation of the
mineral from its undeformed state
(i.e. the state at the reference pressure and temperature).
:rtype: numpy.array (2D)
"""
F = expm(np.einsum("ijkl, kl", self.Psi, np.eye(3)))
return F
@material_property
def unrotated_cell_vectors(self):
"""
:returns: The vectors of the cell [m] constructed from one mole
of formula units after deformation of the mineral from its
undeformed state (i.e. the state at the reference
pressure and temperature). See the documentation for the function
:func:`~burnman.utils.unitcell.cell_parameters_to_vectors`
for the assumed relationships between the cell vectors and
spatial coordinate axes.
:rtype: numpy.array (2D)
"""
return self.deformation_gradient_tensor
@material_property
def deformed_coordinate_frame(self):
"""
:returns: The orientations of the three spatial coordinate axes
after deformation of the mineral [m]. For orthotropic minerals,
this is equal to the identity matrix, as hydrostatic stresses only
induce rotations in monoclinic and triclinic crystals.
:rtype: numpy.array (2D)
"""
if self.orthotropic:
return np.eye(3)
else:
M = self.unrotated_cell_vectors
Q = np.empty((3, 3))
Q[0] = M[0] / np.linalg.norm(M[0])
Q[2] = np.cross(M[0], M[1]) / np.linalg.norm(np.cross(M[0], M[1]))
Q[1] = np.cross(Q[2], Q[0])
return Q
@material_property
def rotation_matrix(self):
"""
:returns: The matrix required to rotate the properties of the deformed
mineral into the deformed coordinate frame. For orthotropic
minerals, this is equal to the identity matrix.
:rtype: numpy.array (2D)
"""
return self.deformed_coordinate_frame.T
@material_property
def cell_vectors(self):
"""
:returns: The vectors of the cell constructed from one mole
of formula units [m]. See the documentation for the function
:func:`~burnman.utils.unitcell.cell_parameters_to_vectors`
for the assumed relationships between the cell vectors and
spatial coordinate axes.
:rtype: numpy.array (2D)
"""
if self.orthotropic:
return self.unrotated_cell_vectors
else:
return np.einsum(
"ij, jk->ik", self.unrotated_cell_vectors, self.rotation_matrix
)
@material_property
def cell_parameters(self):
"""
:returns: The molar cell parameters of the mineral, given in standard form:
[:math:`a`, :math:`b`, :math:`c`,
:math:`\\alpha`, :math:`\\beta`, :math:`\\gamma`],
where the first three floats are the lengths of the vectors in [m]
defining the cell constructed from one mole of formula units.
The last three floats are angles between vectors
(given in radians). See the documentation for the function
:func:`~burnman.utils.unitcell.cell_parameters_to_vectors`
for the assumed relationships between the cell vectors and
spatial coordinate axes.
:rtype: numpy.array (1D)
"""
return cell_vectors_to_parameters(self.cell_vectors)
@material_property
def shear_modulus(self):
"""
Anisotropic minerals do not (in general) have a single shear modulus.
This function returns a NotImplementedError. Users should instead
consider directly querying the elements in the
isothermal_stiffness_tensor or isentropic_stiffness_tensor.
"""
raise NotImplementedError(
"Anisotropic minerals do not have a shear "
"modulus property. Query "
"the isentropic or isothermal stiffness "
"tensors directory, or use"
"isentropic_shear_modulus_reuss or "
"isentropic_shear_modulus_voigt."
)
@material_property
def isothermal_bulk_modulus(self):
"""
Anisotropic minerals do not have a single isothermal bulk modulus.
This function returns a NotImplementedError. Users should instead
consider either using isothermal_bulk_modulus_reuss,
isothermal_bulk_modulus_voigt,
or directly querying the elements in the isothermal_stiffness_tensor.
"""
raise NotImplementedError(
"isothermal_bulk_modulus is not "
"sufficiently explicit for an "
"anisotropic mineral. Did you mean "
"isothermal_bulk_modulus_reuss?"
)
@material_property
def isentropic_bulk_modulus(self):
"""
Anisotropic minerals do not have a single isentropic bulk modulus.
This function returns a NotImplementedError. Users should instead
consider either using isentropic_bulk_modulus_reuss,
isentropic_bulk_modulus_voigt (both derived from AnisotropicMineral),
or directly querying the elements in the isentropic_stiffness_tensor.
"""
raise NotImplementedError(
"isentropic_bulk_modulus is not "
"sufficiently explicit for an "
"anisotropic mineral. Did you mean "
"isentropic_bulk_modulus_reuss?"
)
isothermal_bulk_modulus_reuss = Mineral.isothermal_bulk_modulus
@material_property
def isothermal_compressibility(self):
"""
Anisotropic minerals do not have a single isentropic compressibility.
This function returns a NotImplementedError. Users should instead
consider either using isothermal_compressibility_reuss,
isothermal_compressibility_voigt (both derived from AnisotropicMineral),
or directly querying the elements in the isothermal_compliance_tensor.
"""
raise NotImplementedError(
"isothermal_compressibility is not "
"sufficiently explicit for an "
"anisotropic mineral. Did you mean "
"isothermal_compressibility_reuss?"
)
@material_property
def isentropic_compressibility(self):
"""
Anisotropic minerals do not have a single isentropic compressibility.
This function returns a NotImplementedError. Users should instead
consider either using isentropic_compressibility_reuss,
isentropic_compressibility_voigt (both derived from AnisotropicMineral),
or directly querying the elements in the isentropic_compliance_tensor.
"""
raise NotImplementedError(
"isentropic_compressibility is not "
"sufficiently explicit for an "
"anisotropic mineral. Did you mean "
"isentropic_compressibility_reuss?"
)
@material_property
def isothermal_bulk_modulus_voigt(self):
"""
:returns: The Voigt bound on the isothermal bulk modulus in [Pa].
:rtype: float
"""
K = (
np.sum(
[
[self.isothermal_stiffness_tensor[i][k] for k in range(3)]
for i in range(3)
]
)
/ 9.0
)
return K
@material_property
def isothermal_compressibility_reuss(self):
"""
:returns: The Reuss bound on the isothermal compressibility in [1/Pa].
:rtype: float
"""
return 1.0 / self.isothermal_bulk_modulus_reuss
beta_T = isothermal_compressibility_reuss
@material_property
def isothermal_compressibility_voigt(self):
"""
:returns: The Voigt bound on the isothermal compressibility in [1/Pa].
:rtype: float
"""
return 1.0 / self.isothermal_bulk_modulus_voigt
@material_property
def isentropic_compressibility_reuss(self):
"""
:returns: The Reuss bound on the isentropic compressibility in [1/Pa].
:rtype: float
"""
return 1.0 / self.isentropic_bulk_modulus_reuss
beta_S = isentropic_compressibility_reuss
@material_property
def isentropic_compressibility_voigt(self):
"""
:returns: The Voigt bound on the isentropic compressibility in [1/Pa].
:rtype: float
"""
return 1.0 / self.isentropic_bulk_modulus_voigt
@material_property
def isothermal_compliance_tensor(self):
"""
:returns: The isothermal compliance tensor [1/Pa]
in Voigt form (:math:`\\mathbb{S}_{\\text{T} pq}`).
:rtype: numpy.array (2D)
"""
S_T = -self.dPsidP_Voigt
if self.orthotropic:
return S_T
else:
R = self.rotation_matrix
S = voigt_notation_to_compliance_tensor(S_T)
S_rotated = np.einsum("mi, nj, ok, pl, ijkl->mnop", R, R, R, R, S)
return contract_compliances(S_rotated)
@material_property
def thermal_expansivity_tensor(self):
"""
:returns: The tensor of thermal expansivities [1/K].
:rtype: numpy.array (2D)
"""
alpha = np.einsum(
"ijkl, kl",
voigt_notation_to_compliance_tensor(self.dPsidT_Voigt),
np.eye(3),
)
if self.orthotropic:
return alpha
else:
R = self.rotation_matrix
return np.einsum("mi, nj, ij->mn", R, R, alpha)
# Derived properties start here
@material_property
def isothermal_stiffness_tensor(self):
"""
:returns: The isothermal stiffness tensor [Pa]
in Voigt form (:math:`\\mathbb{C}_{\\text{T} pq}`).
:rtype: numpy.array (2D)
"""
return np.linalg.inv(self.isothermal_compliance_tensor)
@material_property
def full_isothermal_compliance_tensor(self):
"""
:returns: The isothermal compliance tensor [1/Pa]
in standard form (:math:`\\mathbb{S}_{\\text{T} ijkl}`).
:rtype: numpy.array (4D)
"""
S_Voigt = self.isothermal_compliance_tensor
return voigt_notation_to_compliance_tensor(S_Voigt)
@material_property
def full_isothermal_stiffness_tensor(self):
"""
:returns: The isothermal stiffness tensor [Pa]
in standard form (:math:`\\mathbb{C}_{\\text{T} ijkl}`).
:rtype: numpy.array (4D)
"""
CT = self.isothermal_stiffness_tensor
return voigt_notation_to_stiffness_tensor(CT)
@material_property
def full_isentropic_compliance_tensor(self):
"""
:returns: The isentropic compliance tensor [1/Pa]
in standard form (:math:`\\mathbb{S}_{\\text{N} ijkl}`).
:rtype: numpy.array (4D)
"""
return (
self.full_isothermal_compliance_tensor
- np.einsum(
"ij, kl->ijkl",
self.thermal_expansivity_tensor,
self.thermal_expansivity_tensor,
)
* self.V
* self.temperature
/ self.C_p
)
@material_property
def isentropic_compliance_tensor(self):
"""
:returns: The isentropic compliance tensor [1/Pa]
in Voigt form (:math:`\\mathbb{S}_{\\text{N} pq}`).
:rtype: numpy.array (2D)
"""
S_full = self.full_isentropic_compliance_tensor
return contract_compliances(S_full)
@material_property
def isentropic_stiffness_tensor(self):
"""
:returns: The isentropic stiffness tensor [Pa]
in Voigt form (:math:`\\mathbb{C}_{\\text{N} pq}`).
:rtype: numpy.array (2D)
"""
return np.linalg.inv(self.isentropic_compliance_tensor)
@material_property
def full_isentropic_stiffness_tensor(self):
"""
:returns: The isentropic stiffness tensor [Pa]
in standard form (:math:`\\mathbb{C}_{\\text{N} ijkl}`).
:rtype: numpy.array (4D)
"""
C_Voigt = self.isentropic_stiffness_tensor
return voigt_notation_to_stiffness_tensor(C_Voigt)
@material_property
def grueneisen_tensor(self):
"""
:returns: The grueneisen tensor [unitless].
This is defined by :cite:`BarronMunn1967` as
:math:`\\mathbb{C}_{\\text{N} ijkl} \\alpha_{kl} V/C_{P}`.
:rtype: numpy.array (2D)
"""
return (
np.einsum(
"ijkl, kl->ij",
self.full_isentropic_stiffness_tensor,
self.thermal_expansivity_tensor,
)
* self.molar_volume
/ self.molar_heat_capacity_p
)
@material_property
def grueneisen_parameter(self):
"""
:returns: The scalar grueneisen parameter [unitless].
:rtype: float
"""
return (
self.thermal_expansivity
* self.V
/ (self.isentropic_compressibility_reuss * self.molar_heat_capacity_p)
)
@material_property
def isothermal_compressibility_tensor(self):
"""
:returns: The isothermal compressibility tensor [1/Pa].
:rtype: numpy.array (2D)
"""
return np.einsum(
"ijkl, kl->ij", self.full_isothermal_compliance_tensor, np.eye(3)
)
@material_property
def isentropic_compressibility_tensor(self):
"""
:returns: The isentropic compressibility tensor [1/Pa].
:rtype: numpy.array (2D)
"""
return np.einsum(
"ijkl, kl->ij", self.full_isentropic_compliance_tensor, np.eye(3)
)
@material_property
def thermal_stress_tensor(self):
"""
:returns: The change in stress with temperature at constant strain [Pa/K].
:rtype: numpy.array (2D)
"""
pi = -np.einsum(
"ijkl, kl",
self.full_isothermal_stiffness_tensor,
self.thermal_expansivity_tensor,
)
return pi
@material_property
def molar_isometric_heat_capacity(self):
"""
:returns: The molar heat capacity at constant strain [J/K/mol].
:rtype: float
"""
alpha = self.thermal_expansivity_tensor
pi = self.thermal_stress_tensor
C_isometric = (
self.molar_heat_capacity_p
+ self.V * self.temperature * np.einsum("ij, ij", alpha, pi)
)
return C_isometric
def check_standard_parameters(self, anisotropic_parameters):
if not np.all(anisotropic_parameters[:, :, 0, 0] == 0):
raise Exception(
"anisotropic_parameters_pqmn should be set to " "zero for all m = n = 0"
)
sum_ijij_block = np.sum(anisotropic_parameters[:3, :3, :, :], axis=(0, 1))
if np.abs(sum_ijij_block[1, 0] - 1.0) > 1.0e-5:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal "
"1 for m=1, n=0 for consistency with the volume. "
f"Value is {sum_ijij_block[1, 0]}"
)
for m in range(2, len(sum_ijij_block)):
if np.abs(sum_ijij_block[m, 0]) > 1.0e-10:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal 0 for"
f"m={m}, n=0 for consistency with the volume. "
f"Value is {sum_ijij_block[m, 0]}"
)
for m in range(len(sum_ijij_block)):
for n in range(1, len(sum_ijij_block[0])):
if np.abs(sum_ijij_block[m, n]) > 1.0e-10:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal "
f"0 for m={m}, n={n} for "
"consistency with the volume. "
f"Value is {sum_ijij_block[m, n]}"
)
if cond(anisotropic_parameters[:, :, 1, 0]) > 1 / np.finfo(float).eps:
raise Exception("anisotropic_parameters[:, :, 1, 0] is singular")
sum_lower_left_block = np.sum(anisotropic_parameters[3:, :3, :, :], axis=1)
self.orthotropic = True
for i, s in enumerate(sum_lower_left_block):
if not np.all(np.abs(s) < 1.0e-10):
self.orthotropic = False
| (isotropic_mineral, cell_parameters, anisotropic_parameters, psi_function=None, orthotropic=None) |
10,865 | burnman.classes.anisotropicmineral | __init__ | null | def __init__(
self,
isotropic_mineral,
cell_parameters,
anisotropic_parameters,
psi_function=None,
orthotropic=None,
):
if psi_function is None:
self.check_standard_parameters(anisotropic_parameters)
self.anisotropic_params = {"c": anisotropic_parameters}
self.psi_function = self.standard_psi_function
else:
if not isinstance(orthotropic, bool):
raise Exception(
"If the Psi function is provided, "
"you must specify whether your material is "
"orthotropic as a boolean."
)
self.orthotropic = orthotropic
self.anisotropic_params = anisotropic_parameters
self.psi_function = psi_function
self.cell_vectors_0 = cell_parameters_to_vectors(cell_parameters)
if (
np.abs(np.linalg.det(self.cell_vectors_0) - isotropic_mineral.params["V_0"])
> np.finfo(float).eps
):
factor = np.cbrt(
isotropic_mineral.params["V_0"] / np.linalg.det(self.cell_vectors_0)
)
raise Exception(
"The standard state unit vectors are inconsistent "
"with the volume. Suggest multiplying each "
f"by {factor}."
)
# Note, Psi_0 may be asymmetric, in which case the Voigt contraction
# cannot be applied
self.Psi_0 = np.einsum("ij, kl", logm(self.cell_vectors_0), np.eye(3) / 3.0)
self.isotropic_mineral = isotropic_mineral
if "name" in isotropic_mineral.params:
self.name = isotropic_mineral.params["name"]
Mineral.__init__(
self, isotropic_mineral.params, isotropic_mineral.property_modifiers
)
| (self, isotropic_mineral, cell_parameters, anisotropic_parameters, psi_function=None, orthotropic=None) |
10,866 | burnman.classes.anisotropicmineral | check_standard_parameters | null | def check_standard_parameters(self, anisotropic_parameters):
if not np.all(anisotropic_parameters[:, :, 0, 0] == 0):
raise Exception(
"anisotropic_parameters_pqmn should be set to " "zero for all m = n = 0"
)
sum_ijij_block = np.sum(anisotropic_parameters[:3, :3, :, :], axis=(0, 1))
if np.abs(sum_ijij_block[1, 0] - 1.0) > 1.0e-5:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal "
"1 for m=1, n=0 for consistency with the volume. "
f"Value is {sum_ijij_block[1, 0]}"
)
for m in range(2, len(sum_ijij_block)):
if np.abs(sum_ijij_block[m, 0]) > 1.0e-10:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal 0 for"
f"m={m}, n=0 for consistency with the volume. "
f"Value is {sum_ijij_block[m, 0]}"
)
for m in range(len(sum_ijij_block)):
for n in range(1, len(sum_ijij_block[0])):
if np.abs(sum_ijij_block[m, n]) > 1.0e-10:
raise Exception(
"The sum of the upper 3x3 pq-block of "
"anisotropic_parameters_pqmn must equal "
f"0 for m={m}, n={n} for "
"consistency with the volume. "
f"Value is {sum_ijij_block[m, n]}"
)
if cond(anisotropic_parameters[:, :, 1, 0]) > 1 / np.finfo(float).eps:
raise Exception("anisotropic_parameters[:, :, 1, 0] is singular")
sum_lower_left_block = np.sum(anisotropic_parameters[3:, :3, :, :], axis=1)
self.orthotropic = True
for i, s in enumerate(sum_lower_left_block):
if not np.all(np.abs(s) < 1.0e-10):
self.orthotropic = False
| (self, anisotropic_parameters) |
10,869 | burnman.classes.mineral | debug_print | null | def debug_print(self, indent=""):
print("%s%s" % (indent, self.to_string()))
| (self, indent='') |
10,877 | burnman.classes.mineral | set_method |
Set the equation of state to be used for this mineral.
Takes a string corresponding to any of the predefined
equations of state: 'bm2', 'bm3', 'mgd2', 'mgd3', 'slb2', 'slb3',
'mt', 'hp_tmt', or 'cork'. Alternatively, you can pass a user defined
class which derives from the equation_of_state base class.
After calling set_method(), any existing derived properties
(e.g., elastic parameters or thermodynamic potentials) will be out
of date, so set_state() will need to be called again.
| def set_method(self, equation_of_state):
"""
Set the equation of state to be used for this mineral.
Takes a string corresponding to any of the predefined
equations of state: 'bm2', 'bm3', 'mgd2', 'mgd3', 'slb2', 'slb3',
'mt', 'hp_tmt', or 'cork'. Alternatively, you can pass a user defined
class which derives from the equation_of_state base class.
After calling set_method(), any existing derived properties
(e.g., elastic parameters or thermodynamic potentials) will be out
of date, so set_state() will need to be called again.
"""
if equation_of_state is None:
self.method = None
return
new_method = eos.create(equation_of_state)
if self.method is not None and "equation_of_state" in self.params:
self.method = eos.create(self.params["equation_of_state"])
if type(new_method).__name__ == "instance":
raise Exception(
"Please derive your method from object (see python old style classes)"
)
if (
self.method is not None
and isinstance(new_method, type(self.method)) is False
):
# Warn user that they are changing the EoS
warnings.warn(
"Warning, you are changing the method to "
f"{new_method.__class__.__name__} even though the "
"material is designed to be used with the method "
f"{self.method.__class__.__name__}. "
"This does not overwrite any mineral attributes",
stacklevel=2,
)
self.reset()
self.method = new_method
# Validate the params object on the requested EOS.
try:
self.method.validate_parameters(self.params)
except Exception as e:
print(
f"Mineral {self.to_string()} failed to validate parameters "
f'with message: "{e.message}"'
)
raise
# Invalidate the cache upon resetting the method
self.reset()
| (self, equation_of_state) |
10,878 | burnman.utils.misc | set_state | (copied from set_state):
Set the material to the given pressure and temperature.
:param pressure: The desired pressure in [Pa].
:type pressure: float
:param temperature: The desired temperature in [K].
:type temperature: float
| def copy_documentation(copy_from):
"""
Decorator @copy_documentation(another_function) will copy the documentation found in a different
function (for example from a base class). The docstring applied to some function a() will be ::
(copied from BaseClass.some_function):
<documentation from BaseClass.some_function>
<optionally the documentation found in a()>
"""
def mydecorator(func):
def wrapper(*args):
return func(*args)
old = ""
if func.__doc__:
old = "\n" + func.__doc__
copied_from = ""
if hasattr(copy_from, "__name__"):
copied_from = "(copied from " + copy_from.__name__ + "):\n"
wrapper.__doc__ = copied_from + copy_from.__doc__ + old
wrapper.__name__ = func.__name__
return wrapper
return mydecorator
| (*args) |
10,880 | burnman.classes.anisotropicmineral | standard_psi_function | null | def standard_psi_function(self, f, Pth, params):
# Compute Psi, dPsidPth, dPsidf, needed by most anisotropic properties
c = params["c"]
ns = np.arange(c.shape[-1])
x = c[:, :, 0, :] + c[:, :, 1, :] * f
dPsidf = c[:, :, 1, :]
for i in list(range(2, c.shape[2])):
# non-intuitively, the += operator doesn't simply add in-place,
# so here we overwrite the arrays with new ones
x = x + c[:, :, i, :] * np.power(f, float(i)) / float(i)
dPsidf = dPsidf + c[:, :, i, :] * np.power(f, float(i) - 1.0)
Psi = np.einsum("ikn, n->ik", x, np.power(Pth, ns))
dPsidPth = np.einsum(
"ikn, n->ik", x[:, :, 1:], ns[1:] * np.power(Pth, ns[1:] - 1)
)
dPsidf = np.einsum("ikn, n->ik", dPsidf, np.power(Pth, ns))
return (Psi, dPsidf, dPsidPth)
| (self, f, Pth, params) |
10,881 | burnman.classes.mineral | to_string |
Returns the name of the mineral class
| def to_string(self):
"""
Returns the name of the mineral class
"""
return (
"'"
+ self.__class__.__module__.replace(".minlib_", ".")
+ "."
+ self.__class__.__name__
+ "'"
)
| (self) |
10,882 | burnman.classes.mineral | unroll | null | def unroll(self):
return ([self], [1.0])
| (self) |
10,884 | burnman.classes.layer | BoundaryLayerPerturbation |
A class that implements a temperature perturbation model corresponding to a
simple thermal boundary layer.
The model takes the following form:
T = a*exp((r - r1)/(r0 - r1)*c) + b*exp((r - r0)/(r1 - r0)*c)
The relationships between the input parameters and a, b and c are
given below.
This model is a simpler version of that proposed
by :cite:`Richter1981`.
:param radius_bottom: The radius at the bottom of the layer (r0) [m].
:type radius_bottom: float
:param radius_top: The radius at the top of the layer (r1) [m].
:type radius_top: float
:param rayleigh_number: The Rayleigh number of convection within the layer. The
exponential scale factor is this number to the power of 1/4
(Ra = c^4).
:type rayleigh_number: float
:param temperature_change: The total difference in potential
temperature across the layer [K]. temperature_change = (a + b)*exp(c).
:type temperature_change: float
:param boundary_layer_ratio: The ratio of the linear scale factors (a/b)
corresponding to the thermal boundary layers at the top and bottom of
the layer. A number greater than 1 implies a larger change in
temperature across the top boundary than the bottom boundary.
:type boundary_layer_ratio: float
| class BoundaryLayerPerturbation(object):
"""
A class that implements a temperature perturbation model corresponding to a
simple thermal boundary layer.
The model takes the following form:
T = a*exp((r - r1)/(r0 - r1)*c) + b*exp((r - r0)/(r1 - r0)*c)
The relationships between the input parameters and a, b and c are
given below.
This model is a simpler version of that proposed
by :cite:`Richter1981`.
:param radius_bottom: The radius at the bottom of the layer (r0) [m].
:type radius_bottom: float
:param radius_top: The radius at the top of the layer (r1) [m].
:type radius_top: float
:param rayleigh_number: The Rayleigh number of convection within the layer. The
exponential scale factor is this number to the power of 1/4
(Ra = c^4).
:type rayleigh_number: float
:param temperature_change: The total difference in potential
temperature across the layer [K]. temperature_change = (a + b)*exp(c).
:type temperature_change: float
:param boundary_layer_ratio: The ratio of the linear scale factors (a/b)
corresponding to the thermal boundary layers at the top and bottom of
the layer. A number greater than 1 implies a larger change in
temperature across the top boundary than the bottom boundary.
:type boundary_layer_ratio: float
"""
def __init__(
self,
radius_bottom,
radius_top,
rayleigh_number,
temperature_change,
boundary_layer_ratio,
):
self.r0 = radius_bottom
self.r1 = radius_top
self.Ra = rayleigh_number
self.c = np.power(self.Ra, 1.0 / 4.0)
self.a = temperature_change / (np.exp(self.c) * (1.0 + boundary_layer_ratio))
self.b = -boundary_layer_ratio * self.a
def temperature(self, radii):
"""
Returns the temperature at one or more radii [K].
:param radii: The radii at which to evaluate the temperature.
:type radii: float or numpy.array
:returns: The temperatures at the requested radii.
:rtype: float or numpy.array
"""
return self.a * np.exp(
(radii - self.r1) / (self.r0 - self.r1) * self.c
) + self.b * np.exp((radii - self.r0) / (self.r1 - self.r0) * self.c)
def dTdr(self, radii):
"""
Returns the thermal gradient at one or more radii [K/m].
:param radii: The radii at which to evaluate the thermal gradients.
:type radii: float or numpy.array
:returns: The thermal gradient at the requested radii.
:rtype: float or numpy.array
"""
return (
self.c
/ (self.r0 - self.r1)
* (
self.a * np.exp((radii - self.r1) / (self.r0 - self.r1) * self.c)
- self.b * np.exp((radii - self.r0) / (self.r1 - self.r0) * self.c)
)
)
def set_model_thermal_gradients(self, dTdr_bottom, dTdr_top):
"""
Reparameterizes the model based on the thermal gradients
at the bottom and top of the model.
:param dTdr_bottom: The thermal gradient at the bottom of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_bottom: float
:param dTdr_top: The thermal gradient at the top of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_top: float
"""
def delta_dTdrs(args, dTdr_bottom, dTdr_top):
a, b = args
self.a = a
self.b = b
return [dTdr_bottom - self.dTdr(self.r0), dTdr_top - self.dTdr(self.r1)]
fsolve(delta_dTdrs, [self.a, self.b], args=(dTdr_bottom, dTdr_top))
| (radius_bottom, radius_top, rayleigh_number, temperature_change, boundary_layer_ratio) |
10,885 | burnman.classes.layer | __init__ | null | def __init__(
self,
radius_bottom,
radius_top,
rayleigh_number,
temperature_change,
boundary_layer_ratio,
):
self.r0 = radius_bottom
self.r1 = radius_top
self.Ra = rayleigh_number
self.c = np.power(self.Ra, 1.0 / 4.0)
self.a = temperature_change / (np.exp(self.c) * (1.0 + boundary_layer_ratio))
self.b = -boundary_layer_ratio * self.a
| (self, radius_bottom, radius_top, rayleigh_number, temperature_change, boundary_layer_ratio) |
10,886 | burnman.classes.layer | dTdr |
Returns the thermal gradient at one or more radii [K/m].
:param radii: The radii at which to evaluate the thermal gradients.
:type radii: float or numpy.array
:returns: The thermal gradient at the requested radii.
:rtype: float or numpy.array
| def dTdr(self, radii):
"""
Returns the thermal gradient at one or more radii [K/m].
:param radii: The radii at which to evaluate the thermal gradients.
:type radii: float or numpy.array
:returns: The thermal gradient at the requested radii.
:rtype: float or numpy.array
"""
return (
self.c
/ (self.r0 - self.r1)
* (
self.a * np.exp((radii - self.r1) / (self.r0 - self.r1) * self.c)
- self.b * np.exp((radii - self.r0) / (self.r1 - self.r0) * self.c)
)
)
| (self, radii) |
10,887 | burnman.classes.layer | set_model_thermal_gradients |
Reparameterizes the model based on the thermal gradients
at the bottom and top of the model.
:param dTdr_bottom: The thermal gradient at the bottom of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_bottom: float
:param dTdr_top: The thermal gradient at the top of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_top: float
| def set_model_thermal_gradients(self, dTdr_bottom, dTdr_top):
"""
Reparameterizes the model based on the thermal gradients
at the bottom and top of the model.
:param dTdr_bottom: The thermal gradient at the bottom of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_bottom: float
:param dTdr_top: The thermal gradient at the top of the model [K/m].
Typically negative for a cooling planet.
:type dTdr_top: float
"""
def delta_dTdrs(args, dTdr_bottom, dTdr_top):
a, b = args
self.a = a
self.b = b
return [dTdr_bottom - self.dTdr(self.r0), dTdr_top - self.dTdr(self.r1)]
fsolve(delta_dTdrs, [self.a, self.b], args=(dTdr_bottom, dTdr_top))
| (self, dTdr_bottom, dTdr_top) |
10,888 | burnman.classes.layer | temperature |
Returns the temperature at one or more radii [K].
:param radii: The radii at which to evaluate the temperature.
:type radii: float or numpy.array
:returns: The temperatures at the requested radii.
:rtype: float or numpy.array
| def temperature(self, radii):
"""
Returns the temperature at one or more radii [K].
:param radii: The radii at which to evaluate the temperature.
:type radii: float or numpy.array
:returns: The temperatures at the requested radii.
:rtype: float or numpy.array
"""
return self.a * np.exp(
(radii - self.r1) / (self.r0 - self.r1) * self.c
) + self.b * np.exp((radii - self.r0) / (self.r1 - self.r0) * self.c)
| (self, radii) |
10,889 | burnman.classes.calibrant | Calibrant |
The base class for a pressure calibrant material.
:param calibrant_function: A function that takes either pressure,
temperature and a params object as arguments, returning the volume,
or takes volume, temperature and a params object, returning the pressure.
:type calibrant_function: function
:param calibrant_function_return_type: The return type of the calibrant function.
Valid values are 'pressure' or 'volume'.
:type calibrant_function_return_type: str
:param params: A dictionary containing the parameters required by the
calibrant function.
:type params: dictionary
| class Calibrant(object):
"""
The base class for a pressure calibrant material.
:param calibrant_function: A function that takes either pressure,
temperature and a params object as arguments, returning the volume,
or takes volume, temperature and a params object, returning the pressure.
:type calibrant_function: function
:param calibrant_function_return_type: The return type of the calibrant function.
Valid values are 'pressure' or 'volume'.
:type calibrant_function_return_type: str
:param params: A dictionary containing the parameters required by the
calibrant function.
:type params: dictionary
"""
def __init__(self, calibrant_function, calibrant_function_return_type, params):
if calibrant_function_return_type == "pressure":
self.pressure_function = calibrant_function
self.volume_function = self._volume_using_pressure_function
elif calibrant_function_return_type == "volume":
self.volume_function = calibrant_function
self.pressure_function = self._pressure_using_volume_function
else:
raise Exception(
"calibrant function return type must either " "be pressure or volume"
)
self.calibrant_function = calibrant_function
self.params = params
def _volume_using_pressure_function(self, pressure, temperature, params):
"""
Helper function to compute volume iteratively by Brent's method using
a function of the form pressure(volume, temperature).
"""
def func(x):
return self.pressure_function(x, temperature, params) - pressure
try:
sol = bracket(func, params["V_0"], 1.0e-2 * params["V_0"])
except ValueError:
raise ValueError(
"Cannot find a volume, perhaps you are outside "
"of the range of validity for the equation "
"of state?"
)
return opt.brentq(func, sol[0], sol[1])
def _pressure_using_volume_function(self, volume, temperature, params):
"""
Helper function to compute pressure iteratively by Brent's method using
a function of the form volume(pressure, temperature).
"""
def func(x):
(self.volume_function(x, temperature, params) - volume)
try:
sol = bracket(func, 0.0, 300.0e9)
except ValueError:
raise ValueError(
"Cannot find a pressure, perhaps you are outside "
"of the range of validity for the equation "
"of state?"
)
return opt.brentq(func, sol[0], sol[1])
def pressure(self, volume, temperature, VT_covariance=None):
"""
Returns the pressure of the calibrant as a function of
volume, temperature and (optionally) a volume-temperature
variance-covariance matrix.
:param volume: The volume of the calibrant [m^3/mol].
:type volume: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param VT_covariance: The volume-temperature
variance-covariance matrix [optional].
:type VT_covariance: 2x2 numpy.array
:returns: The pressure of the calibrant [Pa] and the
pressure-volume-temperature variance-covariance matrix
if PT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
"""
if VT_covariance is None:
return self.pressure_function(volume, temperature, self.params)
else:
# Here we take the centered differences
# We could alternatively use thermodynamic properties
# but these have not yet been implemented.
dV = volume / 1.0e7
dT = 0.01
PdV0 = self.pressure_function(volume - dV / 2.0, temperature, self.params)
PdV1 = self.pressure_function(volume + dV / 2.0, temperature, self.params)
PdT0 = self.pressure_function(volume, temperature - dT / 2.0, self.params)
PdT1 = self.pressure_function(volume, temperature + dT / 2.0, self.params)
pressure = (PdV0 + PdV1 + PdT0 + PdT1) / 4.0
gradPVT = np.zeros((2, 3))
gradPVT[:, 1:] = np.eye(2)
gradPVT[:, 0] = [(PdV1 - PdV0) / dV, (PdT1 - PdT0) / dT]
PVT_covariance = gradPVT.T.dot(VT_covariance).dot(gradPVT)
return pressure, PVT_covariance
def volume(self, pressure, temperature, PT_covariance=None):
"""
Returns the volume of the calibrant as a function of
pressure, temperature and (optionally) a pressure-temperature
variance-covariance matrix.
:param pressure: The pressure of the calibrant [Pa].
:type pressure: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param PT_covariance: The pressure-temperature
variance-covariance matrix [optional].
:type PT_covariance: 2x2 numpy.array
:returns: The volume of the calibrant [m^3/mol] and
the volume-pressure-temperature variance-covariance matrix
if VT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
"""
if PT_covariance is None:
return self.volume_function(pressure, temperature, self.params)
else:
# Here we take the centered differences
# We could alternatively use thermodynamic properties
# but these have not yet been implemented.
dP = 100.0
dT = 0.01
VdP0 = self.volume_function(pressure - dP / 2.0, temperature, self.params)
VdP1 = self.volume_function(pressure + dP / 2.0, temperature, self.params)
VdT0 = self.volume_function(pressure, temperature - dT / 2.0, self.params)
VdT1 = self.volume_function(pressure, temperature + dT / 2.0, self.params)
volume = (VdP0 + VdP1 + VdT0 + VdT1) / 4.0
gradVPT = np.zeros((2, 3))
gradVPT[:, 1:] = np.eye(2)
gradVPT[:, 0] = [(VdP1 - VdP0) / dP, (VdT1 - VdT0) / dT]
VPT_covariance = gradVPT.T.dot(PT_covariance).dot(gradVPT)
return volume, VPT_covariance
| (calibrant_function, calibrant_function_return_type, params) |
10,890 | burnman.classes.calibrant | __init__ | null | def __init__(self, calibrant_function, calibrant_function_return_type, params):
if calibrant_function_return_type == "pressure":
self.pressure_function = calibrant_function
self.volume_function = self._volume_using_pressure_function
elif calibrant_function_return_type == "volume":
self.volume_function = calibrant_function
self.pressure_function = self._pressure_using_volume_function
else:
raise Exception(
"calibrant function return type must either " "be pressure or volume"
)
self.calibrant_function = calibrant_function
self.params = params
| (self, calibrant_function, calibrant_function_return_type, params) |
10,891 | burnman.classes.calibrant | _pressure_using_volume_function |
Helper function to compute pressure iteratively by Brent's method using
a function of the form volume(pressure, temperature).
| def _pressure_using_volume_function(self, volume, temperature, params):
"""
Helper function to compute pressure iteratively by Brent's method using
a function of the form volume(pressure, temperature).
"""
def func(x):
(self.volume_function(x, temperature, params) - volume)
try:
sol = bracket(func, 0.0, 300.0e9)
except ValueError:
raise ValueError(
"Cannot find a pressure, perhaps you are outside "
"of the range of validity for the equation "
"of state?"
)
return opt.brentq(func, sol[0], sol[1])
| (self, volume, temperature, params) |
10,892 | burnman.classes.calibrant | _volume_using_pressure_function |
Helper function to compute volume iteratively by Brent's method using
a function of the form pressure(volume, temperature).
| def _volume_using_pressure_function(self, pressure, temperature, params):
"""
Helper function to compute volume iteratively by Brent's method using
a function of the form pressure(volume, temperature).
"""
def func(x):
return self.pressure_function(x, temperature, params) - pressure
try:
sol = bracket(func, params["V_0"], 1.0e-2 * params["V_0"])
except ValueError:
raise ValueError(
"Cannot find a volume, perhaps you are outside "
"of the range of validity for the equation "
"of state?"
)
return opt.brentq(func, sol[0], sol[1])
| (self, pressure, temperature, params) |
10,893 | burnman.classes.calibrant | pressure |
Returns the pressure of the calibrant as a function of
volume, temperature and (optionally) a volume-temperature
variance-covariance matrix.
:param volume: The volume of the calibrant [m^3/mol].
:type volume: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param VT_covariance: The volume-temperature
variance-covariance matrix [optional].
:type VT_covariance: 2x2 numpy.array
:returns: The pressure of the calibrant [Pa] and the
pressure-volume-temperature variance-covariance matrix
if PT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
| def pressure(self, volume, temperature, VT_covariance=None):
"""
Returns the pressure of the calibrant as a function of
volume, temperature and (optionally) a volume-temperature
variance-covariance matrix.
:param volume: The volume of the calibrant [m^3/mol].
:type volume: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param VT_covariance: The volume-temperature
variance-covariance matrix [optional].
:type VT_covariance: 2x2 numpy.array
:returns: The pressure of the calibrant [Pa] and the
pressure-volume-temperature variance-covariance matrix
if PT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
"""
if VT_covariance is None:
return self.pressure_function(volume, temperature, self.params)
else:
# Here we take the centered differences
# We could alternatively use thermodynamic properties
# but these have not yet been implemented.
dV = volume / 1.0e7
dT = 0.01
PdV0 = self.pressure_function(volume - dV / 2.0, temperature, self.params)
PdV1 = self.pressure_function(volume + dV / 2.0, temperature, self.params)
PdT0 = self.pressure_function(volume, temperature - dT / 2.0, self.params)
PdT1 = self.pressure_function(volume, temperature + dT / 2.0, self.params)
pressure = (PdV0 + PdV1 + PdT0 + PdT1) / 4.0
gradPVT = np.zeros((2, 3))
gradPVT[:, 1:] = np.eye(2)
gradPVT[:, 0] = [(PdV1 - PdV0) / dV, (PdT1 - PdT0) / dT]
PVT_covariance = gradPVT.T.dot(VT_covariance).dot(gradPVT)
return pressure, PVT_covariance
| (self, volume, temperature, VT_covariance=None) |
10,894 | burnman.classes.calibrant | volume |
Returns the volume of the calibrant as a function of
pressure, temperature and (optionally) a pressure-temperature
variance-covariance matrix.
:param pressure: The pressure of the calibrant [Pa].
:type pressure: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param PT_covariance: The pressure-temperature
variance-covariance matrix [optional].
:type PT_covariance: 2x2 numpy.array
:returns: The volume of the calibrant [m^3/mol] and
the volume-pressure-temperature variance-covariance matrix
if VT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
| def volume(self, pressure, temperature, PT_covariance=None):
"""
Returns the volume of the calibrant as a function of
pressure, temperature and (optionally) a pressure-temperature
variance-covariance matrix.
:param pressure: The pressure of the calibrant [Pa].
:type pressure: float
:param temperature: The temperature of the calibrant [K].
:type temperature: float
:param PT_covariance: The pressure-temperature
variance-covariance matrix [optional].
:type PT_covariance: 2x2 numpy.array
:returns: The volume of the calibrant [m^3/mol] and
the volume-pressure-temperature variance-covariance matrix
if VT_covariance is provided.
:rtype: float, tuple of a float and a numpy.array (3x3)
"""
if PT_covariance is None:
return self.volume_function(pressure, temperature, self.params)
else:
# Here we take the centered differences
# We could alternatively use thermodynamic properties
# but these have not yet been implemented.
dP = 100.0
dT = 0.01
VdP0 = self.volume_function(pressure - dP / 2.0, temperature, self.params)
VdP1 = self.volume_function(pressure + dP / 2.0, temperature, self.params)
VdT0 = self.volume_function(pressure, temperature - dT / 2.0, self.params)
VdT1 = self.volume_function(pressure, temperature + dT / 2.0, self.params)
volume = (VdP0 + VdP1 + VdT0 + VdT1) / 4.0
gradVPT = np.zeros((2, 3))
gradVPT[:, 1:] = np.eye(2)
gradVPT[:, 0] = [(VdP1 - VdP0) / dP, (VdT1 - VdT0) / dT]
VPT_covariance = gradVPT.T.dot(PT_covariance).dot(gradVPT)
return volume, VPT_covariance
| (self, pressure, temperature, PT_covariance=None) |
10,895 | burnman.classes.combinedmineral | CombinedMineral |
This is the base class for endmembers constructed from a
linear combination of other minerals.
Instances of this class should be initialised with a
list of Mineral instances, a second list containing the
number of moles of each mineral, and (optionally) a
third list containing three floats describing a
free energy adjustment which is linear in pressure and temperature
(i.e. a constant energy [J/mol], entropy [J/K/mol]
and volume adjustment [J/Pa/mol or m^3/mol]).
For example, a crude approximation to a bridgmanite model might be
bdg = CombinedMineral([per, stv], [1.0, 1.0], [-15.e3, 0., 0.])
This class is available as :class:`burnman.CombinedMineral`.
| class CombinedMineral(Mineral):
"""
This is the base class for endmembers constructed from a
linear combination of other minerals.
Instances of this class should be initialised with a
list of Mineral instances, a second list containing the
number of moles of each mineral, and (optionally) a
third list containing three floats describing a
free energy adjustment which is linear in pressure and temperature
(i.e. a constant energy [J/mol], entropy [J/K/mol]
and volume adjustment [J/Pa/mol or m^3/mol]).
For example, a crude approximation to a bridgmanite model might be
bdg = CombinedMineral([per, stv], [1.0, 1.0], [-15.e3, 0., 0.])
This class is available as :class:`burnman.CombinedMineral`.
"""
def __init__(
self,
mineral_list,
molar_amounts,
free_energy_adjustment=[],
name="User-created endmember",
):
model = MechanicalSolution(endmembers=[[m, ""] for m in mineral_list])
self.mixture = Solution(solution_model=model, molar_fractions=molar_amounts)
# Remove elements from the chemical formula if they have
# negligible concentrations
for key, value in list(self.mixture.formula.items()):
if np.abs(value) < 1.0e-10:
self.mixture.formula.pop(key)
self.params = {
"name": name,
"formula": self.mixture.formula,
"equation_of_state": "combined",
"molar_mass": self.mixture.molar_mass,
"n": sum(self.mixture.formula.values()),
}
if free_energy_adjustment != []:
assert len(free_energy_adjustment) == 3
dE, dS, dV = free_energy_adjustment
self.property_modifiers = [
["linear", {"delta_E": dE, "delta_S": dS, "delta_V": dV}]
]
Mineral.__init__(self)
def set_state(self, pressure, temperature):
self.mixture.set_state(pressure, temperature)
Mineral.set_state(self, pressure, temperature)
@material_property
def molar_gibbs(self):
"""
Returns Gibbs free energy of the mineral [J]
Aliased with self.gibbs
"""
return self.mixture.molar_gibbs + self._property_modifiers["G"]
@material_property
def _molar_volume_unmodified(self):
return self.mixture.molar_volume
@material_property
def molar_volume(self):
"""
Returns molar volume of the mineral [m^3/mol]
Aliased with self.V
"""
return self.mixture.molar_volume + self._property_modifiers["dGdP"]
@material_property
def molar_entropy(self):
"""
Returns entropy of the mineral [J]
Aliased with self.S
"""
return self.mixture.molar_entropy - self._property_modifiers["dGdT"]
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the mineral [Pa]
Aliased with self.K_T
"""
K_T_orig = self.mixture.isothermal_bulk_modulus
return self.molar_volume / (
(self._molar_volume_unmodified / K_T_orig)
- self._property_modifiers["d2GdP2"]
)
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the mineral [Pa]
Aliased with self.G
"""
return self.mixture.shear_modulus
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient (alpha) of the mineral [1/K]
Aliased with self.alpha
"""
return (
(self.mixture.thermal_expansivity * self._molar_volume_unmodified)
+ self._property_modifiers["d2GdPdT"]
) / self.molar_volume
@material_property
def molar_heat_capacity_p(self):
"""
Returns heat capacity at constant pressure of the mineral [J/K/mol]
Aliased with self.C_p
"""
return (
self.mixture.molar_heat_capacity_p
- self.temperature * self._property_modifiers["d2GdT2"]
)
"""
Properties from mineral parameters,
Legendre transformations
or Maxwell relations
"""
@material_property
def molar_mass(self):
"""
Returns molar mass of the mineral [kg/mol]
"""
return self.mixture.molar_mass
@material_property
def formula(self):
"""
Returns molar chemical formula of the mineral
"""
return self.mixture.formula
@material_property
def density(self):
"""
Returns density of the mineral [kg/m^3]
Aliased with self.rho
"""
return self.molar_mass / self.molar_volume
@material_property
def molar_internal_energy(self):
"""
Returns molar internal energy of the mineral [J/mol]
Aliased with self.energy
"""
return (
self.molar_gibbs
- self.pressure * self.molar_volume
+ self.temperature * self.molar_entropy
)
@material_property
def molar_helmholtz(self):
"""
Returns molar Helmholtz free energy of the mineral [J/mol]
Aliased with self.helmholtz
"""
return self.molar_gibbs - self.pressure * self.molar_volume
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpy of the mineral [J/mol]
Aliased with self.H
"""
return self.molar_gibbs + self.temperature * self.molar_entropy
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns adiabatic bulk modulus of the mineral [Pa]
Aliased with self.K_S
"""
if self.temperature < 1.0e-10:
return self.isothermal_bulk_modulus
else:
return (
self.isothermal_bulk_modulus
* self.molar_heat_capacity_p
/ self.molar_heat_capacity_v
)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the mineral
(or inverse isothermal bulk modulus) [1/Pa]
Aliased with self.K_T
"""
return 1.0 / self.isothermal_bulk_modulus
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibility of the mineral
(or inverse adiabatic bulk modulus) [1/Pa]
Aliased with self.K_S
"""
return 1.0 / self.adiabatic_bulk_modulus
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the mineral [m/s]
Aliased with self.v_p
"""
return np.sqrt(
(self.adiabatic_bulk_modulus + 4.0 / 3.0 * self.shear_modulus)
/ self.density
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the mineral [m/s]
Aliased with self.v_phi
"""
return np.sqrt(self.adiabatic_bulk_modulus / self.density)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the mineral [m/s]
Aliased with self.v_s
"""
return np.sqrt(self.shear_modulus / self.density)
@material_property
def grueneisen_parameter(self):
"""
Returns grueneisen parameter of the mineral [unitless]
Aliased with self.gr
"""
if self.temperature < 1.0e-12:
return 0.0
else:
return (
self.thermal_expansivity
* self.isothermal_bulk_modulus
* self.molar_volume
/ self.molar_heat_capacity_v
)
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volume of the mineral [J/K/mol]
Aliased with self.C_v
"""
return (
self.molar_heat_capacity_p
- self.molar_volume
* self.temperature
* self.thermal_expansivity
* self.thermal_expansivity
* self.isothermal_bulk_modulus
)
| (mineral_list, molar_amounts, free_energy_adjustment=[], name='User-created endmember') |
10,896 | burnman.classes.combinedmineral | __init__ | null | def __init__(
self,
mineral_list,
molar_amounts,
free_energy_adjustment=[],
name="User-created endmember",
):
model = MechanicalSolution(endmembers=[[m, ""] for m in mineral_list])
self.mixture = Solution(solution_model=model, molar_fractions=molar_amounts)
# Remove elements from the chemical formula if they have
# negligible concentrations
for key, value in list(self.mixture.formula.items()):
if np.abs(value) < 1.0e-10:
self.mixture.formula.pop(key)
self.params = {
"name": name,
"formula": self.mixture.formula,
"equation_of_state": "combined",
"molar_mass": self.mixture.molar_mass,
"n": sum(self.mixture.formula.values()),
}
if free_energy_adjustment != []:
assert len(free_energy_adjustment) == 3
dE, dS, dV = free_energy_adjustment
self.property_modifiers = [
["linear", {"delta_E": dE, "delta_S": dS, "delta_V": dV}]
]
Mineral.__init__(self)
| (self, mineral_list, molar_amounts, free_energy_adjustment=[], name='User-created endmember') |
10,903 | burnman.classes.combinedmineral | set_state | null | def set_state(self, pressure, temperature):
self.mixture.set_state(pressure, temperature)
Mineral.set_state(self, pressure, temperature)
| (self, pressure, temperature) |
10,907 | burnman.classes.composite | Composite |
Base class for a composite material.
The static phases can be minerals or materials,
meaning composite can be nested arbitrarily.
The fractions of the phases can be input
as either 'molar' or 'mass' during instantiation,
and modified (or initialised) after this point by
using set_fractions.
This class is available as ``burnman.Composite``.
| class Composite(Material):
"""
Base class for a composite material.
The static phases can be minerals or materials,
meaning composite can be nested arbitrarily.
The fractions of the phases can be input
as either 'molar' or 'mass' during instantiation,
and modified (or initialised) after this point by
using set_fractions.
This class is available as ``burnman.Composite``.
"""
def __init__(
self, phases, fractions=None, fraction_type="molar", name="Unnamed composite"
):
"""
Create a composite using a list of phases and their fractions (adding to 1.0).
:param phases: List of phases.
:type phases: list of :class:`burnman.Material`
:param fractions: molar or mass fraction for each phase.
:type fractions: list of floats
:param fraction_type: 'molar' or 'mass' (optional, 'molar' as standard)
specify whether molar or mass fractions are specified.
:type fraction_type: str
"""
Material.__init__(self)
assert len(phases) > 0
self.phases = phases
if fractions is not None:
self.set_fractions(fractions, fraction_type)
else:
self.molar_fractions = None
self.set_averaging_scheme("VoigtReussHill")
self.name = name
self.equilibrium_tolerance = 1.0e-3 # J/reaction
self.print_precision = 4 # number of significant figures used by self.__str__
def __str__(self):
string = "Composite: {0}".format(self.name)
try:
string += "\n P, T: {0:.{sf}g} Pa, {1:.{sf}g} K".format(
self.pressure, self.temperature, sf=self.print_precision
)
except:
pass
string += "\nPhase and endmember fractions:"
for phase, fraction in zip(*self.unroll()):
string += "\n {0}: {1:0.{sf}f}".format(
phase.name, fraction, sf=self.print_precision
)
if isinstance(phase, Solution):
for i in range(phase.n_endmembers):
string += "\n {0}: {1:0.{sf}f}".format(
phase.endmember_names[i],
phase.molar_fractions[i],
sf=self.print_precision,
)
return string
def set_fractions(self, fractions, fraction_type="molar"):
"""
Change the fractions of the phases of this Composite.
Resets cached properties
:param fractions: list or numpy array of floats
molar or mass fraction for each phase.
:param fraction_type: 'molar' or 'mass'
specify whether molar or mass fractions are specified.
"""
assert len(self.phases) == len(fractions)
if isinstance(fractions, list):
fractions = np.array(fractions)
try:
total = sum(fractions)
except TypeError:
raise Exception(
"Since v0.8, burnman.Composite takes an array of Materials, "
"then an array of fractions"
)
assert np.all(fractions >= -1e-12)
self.reset()
if abs(total - 1.0) > 1e-12:
warnings.warn(
"Warning: list of fractions does not add "
f"up to one but {total:g}. Normalizing."
)
fractions /= total
if fraction_type == "molar":
molar_fractions = fractions
elif fraction_type == "mass":
molar_fractions = self._mass_to_molar_fractions(self.phases, fractions)
else:
raise Exception(
"Fraction type not recognised. " "Please use 'molar' or mass"
)
# Set minimum value of a molar fraction at 0.0 (rather than -1.e-12)
self.molar_fractions = molar_fractions.clip(0.0)
def set_method(self, method):
"""
set the same equation of state method for all the phases in the composite
"""
for phase in self.phases:
phase.set_method(method)
# Clear the cache on resetting method
self.reset()
def set_averaging_scheme(self, averaging_scheme):
"""
Set the averaging scheme for the moduli in the composite.
Default is set to VoigtReussHill, when Composite is initialized.
"""
if type(averaging_scheme) == str:
self.averaging_scheme = getattr(averaging_schemes, averaging_scheme)()
else:
self.averaging_scheme = averaging_scheme
# Clear the cache on resetting averaging scheme
self.reset()
def set_state(self, pressure, temperature):
"""
Update the material to the given pressure [Pa] and temperature [K].
"""
Material.set_state(self, pressure, temperature)
for phase in self.phases:
phase.set_state(pressure, temperature)
def debug_print(self, indent=""):
print("{0}Composite: {1}".format(indent, self.name))
indent += " "
if self.molar_fractions is None:
for i, phase in enumerate(self.phases):
phase.debug_print(indent + " ")
else:
for i, phase in enumerate(self.phases):
print("%s%g of" % (indent, self.molar_fractions[i]))
phase.debug_print(indent + " ")
def unroll(self):
if self.molar_fractions is None:
raise Exception("Unroll only works if the composite has defined fractions.")
phases = []
fractions = []
for i, phase in enumerate(self.phases):
p_mineral, p_fraction = phase.unroll()
check_pairs(p_mineral, p_fraction)
fractions.extend([f * self.molar_fractions[i] for f in p_fraction])
phases.extend(p_mineral)
return phases, fractions
def to_string(self):
"""
return the name of the composite
"""
return "{0}: {1}".format(self.__class__.__name__, self.name)
@material_property
def formula(self):
"""
Returns molar chemical formula of the composite
"""
return sum_formulae([ph.formula for ph in self.phases], self.molar_fractions)
@material_property
def molar_internal_energy(self):
"""
Returns molar internal energy of the mineral [J/mol]
Aliased with self.energy
"""
U = sum(
phase.molar_internal_energy * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
)
return U
@material_property
def molar_gibbs(self):
"""
Returns molar Gibbs free energy of the composite [J/mol]
Aliased with self.gibbs
"""
G = sum(
phase.molar_gibbs * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
)
return G
@material_property
def molar_helmholtz(self):
"""
Returns molar Helmholtz free energy of the mineral [J/mol]
Aliased with self.helmholtz
"""
F = sum(
phase.molar_helmholtz * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
)
return F
@material_property
def molar_volume(self):
"""
Returns molar volume of the composite [m^3/mol]
Aliased with self.V
"""
volumes = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
return np.sum(volumes)
@material_property
def molar_mass(self):
"""
Returns molar mass of the composite [kg/mol]
"""
return sum(
[
phase.molar_mass * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
@material_property
def density(self):
"""
Compute the density of the composite based on the molar volumes and masses
Aliased with self.rho
"""
densities = np.array([phase.density for phase in self.phases])
volumes = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
return self.averaging_scheme.average_density(volumes, densities)
@material_property
def molar_entropy(self):
"""
Returns enthalpy of the mineral [J]
Aliased with self.S
"""
S = sum(
phase.molar_entropy * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
)
return S
@material_property
def molar_enthalpy(self):
"""
Returns enthalpy of the mineral [J]
Aliased with self.H
"""
H = sum(
phase.molar_enthalpy * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
)
return H
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the composite [Pa]
Aliased with self.K_T
"""
V_frac = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
K_ph = np.array([phase.isothermal_bulk_modulus for phase in self.phases])
G_ph = np.array([phase.shear_modulus for phase in self.phases])
return self.averaging_scheme.average_bulk_moduli(V_frac, K_ph, G_ph)
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns adiabatic bulk modulus of the mineral [Pa]
Aliased with self.K_S
"""
V_frac = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
K_ph = np.array([phase.adiabatic_bulk_modulus for phase in self.phases])
G_ph = np.array([phase.shear_modulus for phase in self.phases])
return self.averaging_scheme.average_bulk_moduli(V_frac, K_ph, G_ph)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the composite
(or inverse isothermal bulk modulus) [1/Pa]
Aliased with self.beta_T
"""
return 1.0 / self.isothermal_bulk_modulus
@material_property
def adiabatic_compressibility(self):
"""
Returns isothermal compressibility of the composite
(or inverse isothermal bulk modulus) [1/Pa]
Aliased with self.beta_S
"""
return 1.0 / self.adiabatic_bulk_modulus
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the mineral [Pa]
Aliased with self.G
"""
V_frac = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
K_ph = np.array([phase.adiabatic_bulk_modulus for phase in self.phases])
G_ph = np.array([phase.shear_modulus for phase in self.phases])
return self.averaging_scheme.average_shear_moduli(V_frac, K_ph, G_ph)
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the composite [m/s]
Aliased with self.v_p
"""
return np.sqrt(
(self.adiabatic_bulk_modulus + 4.0 / 3.0 * self.shear_modulus)
/ self.density
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the composite [m/s]
Aliased with self.v_phi
"""
return np.sqrt(self.adiabatic_bulk_modulus / self.density)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the composite [m/s]
Aliased with self.v_s
"""
return np.sqrt(self.shear_modulus / self.density)
@material_property
def grueneisen_parameter(self):
"""
Returns grueneisen parameter of the composite [unitless]
Aliased with self.gr
"""
return (
self.thermal_expansivity
* self.isothermal_bulk_modulus
* self.molar_volume
/ self.molar_heat_capacity_v
)
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient of the composite [1/K]
Aliased with self.alpha
"""
volumes = np.array(
[
phase.molar_volume * molar_fraction
for (phase, molar_fraction) in zip(self.phases, self.molar_fractions)
]
)
alphas = np.array([phase.thermal_expansivity for phase in self.phases])
return self.averaging_scheme.average_thermal_expansivity(volumes, alphas)
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar_heat capacity at constant volume of the composite [J/K/mol]
Aliased with self.C_v
"""
c_v = np.array([phase.molar_heat_capacity_v for phase in self.phases])
return self.averaging_scheme.average_heat_capacity_v(self.molar_fractions, c_v)
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar heat capacity at constant pressure of the composite [J/K/mol]
Aliased with self.C_p
"""
c_p = np.array([phase.molar_heat_capacity_p for phase in self.phases])
return self.averaging_scheme.average_heat_capacity_p(self.molar_fractions, c_p)
@material_property
def endmember_partial_gibbs(self):
"""
Returns the partial Gibbs energies for all
the endmember minerals in the Composite
"""
partial_gibbs = np.empty(self.n_endmembers)
j = 0
for i, n_endmembers in enumerate(self.endmembers_per_phase):
if n_endmembers == 1:
partial_gibbs[j] = self.phases[i].gibbs
else:
partial_gibbs[j : j + n_endmembers] = self.phases[i].partial_gibbs
j += n_endmembers
return partial_gibbs
@material_property
def reaction_affinities(self):
"""
Returns the affinities corresponding to each reaction in reaction_basis
"""
return self.reaction_basis.dot(self.endmember_partial_gibbs)
@material_property
def equilibrated(self):
"""
Returns True if the reaction affinities are all zero
within a given tolerance given by self.equilibrium_tolerance.
"""
return np.all(np.abs(self.reaction_affinities) < self.equilibrium_tolerance)
def set_components(self, components):
"""
Sets the components and components_array attributes of the
composite material. The components attribute is a list of dictionaries
containing the chemical formulae of the components.
The components_array attribute is a 2D numpy array describing the
linear transformation between endmember amounts and component amounts.
The components do not need to be linearly independent, not do they need
to form a complete basis set for the composite.
However, it must be possible to obtain the composition of each
component from a linear sum of the endmember compositions of
the composite. For example, if the composite was composed of
MgSiO3 and Mg2SiO4, SiO2 would be a valid component, but Si would not.
The method raises an exception if any of the chemical potentials are
not defined by the assemblage.
:param components: List of formulae of the components.
:type components: list of dictionaries
"""
# Convert components into array form
b = np.array(
[
[component[el] if el in component else 0.0 for component in components]
for el in self.elements
]
)
# Solve to find a set of endmember proportions that
# satisfy each of the component formulae
p = np.linalg.lstsq(self.stoichiometric_array.T, b, rcond=None)
res = np.abs((self.stoichiometric_array.T.dot(p[0]) - b).T)
res = np.sum(res, axis=1)
# Check that all components can be described by linear sums of
# the endmembers
if not np.all(res < 1.0e-12):
bad_indices = np.argwhere(res > 1.0e-12)
raise Exception(
f"Components {bad_indices} not defined by " "prescribed assemblage"
)
self.components = components
self.component_array = p[0]
def chemical_potential(self, components=None):
"""
Returns the chemical potentials of the currently defined components
in the composite. Raises an exception if
the assemblage is not equilibrated.
:param components: List of formulae of the desired components.
If not specified, the method uses the components specified
by a previous call to set_components.
:type components: list of dictionaries
:returns: The chemical potentials of the desired components in the
equilibrium composite.
:rtype: numpy.array of floats
"""
if not self.equilibrated:
raise Exception(
"This composite is not equilibrated, so "
"it cannot have a defined chemical potential."
)
if components is not None:
self.set_components(components)
# Return the chemical potential of each component
return np.dot(self.component_array.T, self.endmember_partial_gibbs)
def _mass_to_molar_fractions(self, phases, mass_fractions):
"""
Converts a set of mass fractions for phases into a set of molar fractions.
:param phases: The list of phases for which fractions should be converted.
:type phases: list of :class:`burnman.Material`
:param mass_fractions: An array of mass fractions of the input phases.
:type mass_fractions: numpy.array of floats
:returns: An array of molar fractions corresponding to the
input molar fractions.
:rtype: numpy.array of floats
"""
molar_masses = np.array([phase.molar_mass for phase in phases])
moles = mass_fractions / molar_masses
return moles / sum(moles)
@cached_property
def stoichiometric_matrix(self):
"""
An sympy Matrix where each element M[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
def f(i, j):
e = self.elements[j]
if e in self.endmember_formulae[i]:
return nsimplify(self.endmember_formulae[i][e])
else:
return 0
return Matrix(self.n_endmembers, self.n_elements, f)
@cached_property
def stoichiometric_array(self):
"""
An array where each element arr[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
return np.array(self.stoichiometric_matrix).astype(float)
@cached_property
def reaction_basis(self):
"""
An array where each element arr[i,j] corresponds
to the number of moles of endmember[j] involved in reaction[i].
"""
reaction_basis = np.array(
[v[:] for v in self.stoichiometric_matrix.T.nullspace()], dtype=float
)
if len(reaction_basis) == 0:
reaction_basis = np.empty((0, self.n_endmembers))
return reaction_basis
@cached_property
def reaction_basis_as_strings(self):
"""
Returns a list of string representations of all the reactions in
reaction_basis.
"""
return reaction_matrix_as_strings(self.reaction_basis, self.endmember_names)
@cached_property
def n_reactions(self):
"""
The number of reactions in reaction_basis.
"""
return len(self.reaction_basis[:, 0])
@cached_property
def independent_element_indices(self):
"""
A list of an independent set of element indices. If the amounts of
these elements are known (element_amounts),
the amounts of the other elements can be
inferred by
-compositional_null_basis[independent_element_indices].dot(element_amounts)
"""
return sorted(independent_row_indices(self.stoichiometric_matrix.T))
@cached_property
def dependent_element_indices(self):
"""
The element indices not included in the independent list.
"""
return [
i
for i in range(self.n_elements)
if i not in self.independent_element_indices
]
@cached_property
def reduced_stoichiometric_array(self):
"""
The stoichiometric array including only the independent elements
"""
return self.stoichiometric_array[:, self.independent_element_indices]
@cached_property
def compositional_null_basis(self):
"""
An array N such that N.b = 0 for all bulk compositions that can
be produced with a linear sum of the endmembers in the composite.
"""
null_basis = np.array(
[v[:] for v in self.stoichiometric_matrix.nullspace()], dtype=float
)
if null_basis.shape[0] != 0:
M = null_basis[:, self.dependent_element_indices]
assert (M.shape[0] == M.shape[1]) and (M == np.eye(M.shape[0])).all()
return null_basis
@cached_property
def endmember_formulae(self):
"""
A list of the formulae in the composite.
"""
self._set_endmember_properties()
return self.__dict__["endmember_formulae"]
@cached_property
def endmember_names(self):
"""
A list of the endmember names contained in the composite.
Mineral names are returned as given in Mineral.name.
Solution endmember names are given in the format
`Mineral.name in Solution.name`.
"""
self._set_endmember_properties()
return self.__dict__["endmember_names"]
@cached_property
def endmembers_per_phase(self):
"""
A list of integers corresponding to the number of endmembers
stored within each phase.
"""
self._set_endmember_properties()
return self.__dict__["endmembers_per_phase"]
@cached_property
def elements(self):
"""
A list of the elements which could be contained in the composite,
returned in the IUPAC element order.
"""
self._set_endmember_properties()
return self.__dict__["elements"]
@cached_property
def n_endmembers(self):
"""
Returns the number of endmembers in the composite.
"""
return len(self.endmember_names)
@cached_property
def n_elements(self):
"""
Returns the total number of distinct elements
which might be in the composite.
"""
return len(self.elements)
def _set_endmember_properties(self):
"""
Sets endmember_formulae, endmember_names, endmembers_per_phase and
elements as properties of the Composite. This helper function
is used to set all properties at the same time while still allowing
the properties to be stored and documented as individual
cached_properties.
"""
endmember_formulae = []
endmember_names = []
endmembers_per_phase = []
for ph_idx, ph in enumerate(self.phases):
if isinstance(ph, Solution):
endmember_formulae.extend(ph.endmember_formulae)
endmember_names.extend(
[name + " in " + ph.name for name in ph.endmember_names]
)
endmembers_per_phase.append(ph.n_endmembers)
elif isinstance(ph, Mineral):
endmember_formulae.append(ph.formula)
endmember_names.append(ph.name)
endmembers_per_phase.append(1)
else:
raise Exception(
"Unsupported Material type, can only read"
"burnman.Mineral or burnman.Solution"
)
# Populate the stoichiometric matrix
keys = []
for f in endmember_formulae:
keys.extend(f.keys())
# Save to dict so that we only need to do this once
self.__dict__["endmember_formulae"] = endmember_formulae
self.__dict__["endmember_names"] = endmember_names
self.__dict__["endmembers_per_phase"] = endmembers_per_phase
self.__dict__["elements"] = sort_element_list_to_IUPAC_order(set(keys))
| (phases, fractions=None, fraction_type='molar', name='Unnamed composite') |
10,908 | burnman.classes.composite | __init__ |
Create a composite using a list of phases and their fractions (adding to 1.0).
:param phases: List of phases.
:type phases: list of :class:`burnman.Material`
:param fractions: molar or mass fraction for each phase.
:type fractions: list of floats
:param fraction_type: 'molar' or 'mass' (optional, 'molar' as standard)
specify whether molar or mass fractions are specified.
:type fraction_type: str
| def __init__(
self, phases, fractions=None, fraction_type="molar", name="Unnamed composite"
):
"""
Create a composite using a list of phases and their fractions (adding to 1.0).
:param phases: List of phases.
:type phases: list of :class:`burnman.Material`
:param fractions: molar or mass fraction for each phase.
:type fractions: list of floats
:param fraction_type: 'molar' or 'mass' (optional, 'molar' as standard)
specify whether molar or mass fractions are specified.
:type fraction_type: str
"""
Material.__init__(self)
assert len(phases) > 0
self.phases = phases
if fractions is not None:
self.set_fractions(fractions, fraction_type)
else:
self.molar_fractions = None
self.set_averaging_scheme("VoigtReussHill")
self.name = name
self.equilibrium_tolerance = 1.0e-3 # J/reaction
self.print_precision = 4 # number of significant figures used by self.__str__
| (self, phases, fractions=None, fraction_type='molar', name='Unnamed composite') |
10,909 | burnman.classes.composite | __str__ | null | def __str__(self):
string = "Composite: {0}".format(self.name)
try:
string += "\n P, T: {0:.{sf}g} Pa, {1:.{sf}g} K".format(
self.pressure, self.temperature, sf=self.print_precision
)
except:
pass
string += "\nPhase and endmember fractions:"
for phase, fraction in zip(*self.unroll()):
string += "\n {0}: {1:0.{sf}f}".format(
phase.name, fraction, sf=self.print_precision
)
if isinstance(phase, Solution):
for i in range(phase.n_endmembers):
string += "\n {0}: {1:0.{sf}f}".format(
phase.endmember_names[i],
phase.molar_fractions[i],
sf=self.print_precision,
)
return string
| (self) |
10,910 | burnman.classes.composite | _mass_to_molar_fractions |
Converts a set of mass fractions for phases into a set of molar fractions.
:param phases: The list of phases for which fractions should be converted.
:type phases: list of :class:`burnman.Material`
:param mass_fractions: An array of mass fractions of the input phases.
:type mass_fractions: numpy.array of floats
:returns: An array of molar fractions corresponding to the
input molar fractions.
:rtype: numpy.array of floats
| def _mass_to_molar_fractions(self, phases, mass_fractions):
"""
Converts a set of mass fractions for phases into a set of molar fractions.
:param phases: The list of phases for which fractions should be converted.
:type phases: list of :class:`burnman.Material`
:param mass_fractions: An array of mass fractions of the input phases.
:type mass_fractions: numpy.array of floats
:returns: An array of molar fractions corresponding to the
input molar fractions.
:rtype: numpy.array of floats
"""
molar_masses = np.array([phase.molar_mass for phase in phases])
moles = mass_fractions / molar_masses
return moles / sum(moles)
| (self, phases, mass_fractions) |
10,911 | burnman.classes.composite | _set_endmember_properties |
Sets endmember_formulae, endmember_names, endmembers_per_phase and
elements as properties of the Composite. This helper function
is used to set all properties at the same time while still allowing
the properties to be stored and documented as individual
cached_properties.
| def _set_endmember_properties(self):
"""
Sets endmember_formulae, endmember_names, endmembers_per_phase and
elements as properties of the Composite. This helper function
is used to set all properties at the same time while still allowing
the properties to be stored and documented as individual
cached_properties.
"""
endmember_formulae = []
endmember_names = []
endmembers_per_phase = []
for ph_idx, ph in enumerate(self.phases):
if isinstance(ph, Solution):
endmember_formulae.extend(ph.endmember_formulae)
endmember_names.extend(
[name + " in " + ph.name for name in ph.endmember_names]
)
endmembers_per_phase.append(ph.n_endmembers)
elif isinstance(ph, Mineral):
endmember_formulae.append(ph.formula)
endmember_names.append(ph.name)
endmembers_per_phase.append(1)
else:
raise Exception(
"Unsupported Material type, can only read"
"burnman.Mineral or burnman.Solution"
)
# Populate the stoichiometric matrix
keys = []
for f in endmember_formulae:
keys.extend(f.keys())
# Save to dict so that we only need to do this once
self.__dict__["endmember_formulae"] = endmember_formulae
self.__dict__["endmember_names"] = endmember_names
self.__dict__["endmembers_per_phase"] = endmembers_per_phase
self.__dict__["elements"] = sort_element_list_to_IUPAC_order(set(keys))
| (self) |
10,912 | burnman.classes.composite | chemical_potential |
Returns the chemical potentials of the currently defined components
in the composite. Raises an exception if
the assemblage is not equilibrated.
:param components: List of formulae of the desired components.
If not specified, the method uses the components specified
by a previous call to set_components.
:type components: list of dictionaries
:returns: The chemical potentials of the desired components in the
equilibrium composite.
:rtype: numpy.array of floats
| def chemical_potential(self, components=None):
"""
Returns the chemical potentials of the currently defined components
in the composite. Raises an exception if
the assemblage is not equilibrated.
:param components: List of formulae of the desired components.
If not specified, the method uses the components specified
by a previous call to set_components.
:type components: list of dictionaries
:returns: The chemical potentials of the desired components in the
equilibrium composite.
:rtype: numpy.array of floats
"""
if not self.equilibrated:
raise Exception(
"This composite is not equilibrated, so "
"it cannot have a defined chemical potential."
)
if components is not None:
self.set_components(components)
# Return the chemical potential of each component
return np.dot(self.component_array.T, self.endmember_partial_gibbs)
| (self, components=None) |
10,914 | burnman.classes.composite | debug_print | null | def debug_print(self, indent=""):
print("{0}Composite: {1}".format(indent, self.name))
indent += " "
if self.molar_fractions is None:
for i, phase in enumerate(self.phases):
phase.debug_print(indent + " ")
else:
for i, phase in enumerate(self.phases):
print("%s%g of" % (indent, self.molar_fractions[i]))
phase.debug_print(indent + " ")
| (self, indent='') |
10,918 | burnman.classes.composite | set_averaging_scheme |
Set the averaging scheme for the moduli in the composite.
Default is set to VoigtReussHill, when Composite is initialized.
| def set_averaging_scheme(self, averaging_scheme):
"""
Set the averaging scheme for the moduli in the composite.
Default is set to VoigtReussHill, when Composite is initialized.
"""
if type(averaging_scheme) == str:
self.averaging_scheme = getattr(averaging_schemes, averaging_scheme)()
else:
self.averaging_scheme = averaging_scheme
# Clear the cache on resetting averaging scheme
self.reset()
| (self, averaging_scheme) |
10,919 | burnman.classes.composite | set_components |
Sets the components and components_array attributes of the
composite material. The components attribute is a list of dictionaries
containing the chemical formulae of the components.
The components_array attribute is a 2D numpy array describing the
linear transformation between endmember amounts and component amounts.
The components do not need to be linearly independent, not do they need
to form a complete basis set for the composite.
However, it must be possible to obtain the composition of each
component from a linear sum of the endmember compositions of
the composite. For example, if the composite was composed of
MgSiO3 and Mg2SiO4, SiO2 would be a valid component, but Si would not.
The method raises an exception if any of the chemical potentials are
not defined by the assemblage.
:param components: List of formulae of the components.
:type components: list of dictionaries
| def set_components(self, components):
"""
Sets the components and components_array attributes of the
composite material. The components attribute is a list of dictionaries
containing the chemical formulae of the components.
The components_array attribute is a 2D numpy array describing the
linear transformation between endmember amounts and component amounts.
The components do not need to be linearly independent, not do they need
to form a complete basis set for the composite.
However, it must be possible to obtain the composition of each
component from a linear sum of the endmember compositions of
the composite. For example, if the composite was composed of
MgSiO3 and Mg2SiO4, SiO2 would be a valid component, but Si would not.
The method raises an exception if any of the chemical potentials are
not defined by the assemblage.
:param components: List of formulae of the components.
:type components: list of dictionaries
"""
# Convert components into array form
b = np.array(
[
[component[el] if el in component else 0.0 for component in components]
for el in self.elements
]
)
# Solve to find a set of endmember proportions that
# satisfy each of the component formulae
p = np.linalg.lstsq(self.stoichiometric_array.T, b, rcond=None)
res = np.abs((self.stoichiometric_array.T.dot(p[0]) - b).T)
res = np.sum(res, axis=1)
# Check that all components can be described by linear sums of
# the endmembers
if not np.all(res < 1.0e-12):
bad_indices = np.argwhere(res > 1.0e-12)
raise Exception(
f"Components {bad_indices} not defined by " "prescribed assemblage"
)
self.components = components
self.component_array = p[0]
| (self, components) |
10,920 | burnman.classes.composite | set_fractions |
Change the fractions of the phases of this Composite.
Resets cached properties
:param fractions: list or numpy array of floats
molar or mass fraction for each phase.
:param fraction_type: 'molar' or 'mass'
specify whether molar or mass fractions are specified.
| def set_fractions(self, fractions, fraction_type="molar"):
"""
Change the fractions of the phases of this Composite.
Resets cached properties
:param fractions: list or numpy array of floats
molar or mass fraction for each phase.
:param fraction_type: 'molar' or 'mass'
specify whether molar or mass fractions are specified.
"""
assert len(self.phases) == len(fractions)
if isinstance(fractions, list):
fractions = np.array(fractions)
try:
total = sum(fractions)
except TypeError:
raise Exception(
"Since v0.8, burnman.Composite takes an array of Materials, "
"then an array of fractions"
)
assert np.all(fractions >= -1e-12)
self.reset()
if abs(total - 1.0) > 1e-12:
warnings.warn(
"Warning: list of fractions does not add "
f"up to one but {total:g}. Normalizing."
)
fractions /= total
if fraction_type == "molar":
molar_fractions = fractions
elif fraction_type == "mass":
molar_fractions = self._mass_to_molar_fractions(self.phases, fractions)
else:
raise Exception(
"Fraction type not recognised. " "Please use 'molar' or mass"
)
# Set minimum value of a molar fraction at 0.0 (rather than -1.e-12)
self.molar_fractions = molar_fractions.clip(0.0)
| (self, fractions, fraction_type='molar') |
10,921 | burnman.classes.composite | set_method |
set the same equation of state method for all the phases in the composite
| def set_method(self, method):
"""
set the same equation of state method for all the phases in the composite
"""
for phase in self.phases:
phase.set_method(method)
# Clear the cache on resetting method
self.reset()
| (self, method) |
10,922 | burnman.classes.composite | set_state |
Update the material to the given pressure [Pa] and temperature [K].
| def set_state(self, pressure, temperature):
"""
Update the material to the given pressure [Pa] and temperature [K].
"""
Material.set_state(self, pressure, temperature)
for phase in self.phases:
phase.set_state(pressure, temperature)
| (self, pressure, temperature) |
10,924 | burnman.classes.composite | to_string |
return the name of the composite
| def to_string(self):
"""
return the name of the composite
"""
return "{0}: {1}".format(self.__class__.__name__, self.name)
| (self) |
10,925 | burnman.classes.composite | unroll | null | def unroll(self):
if self.molar_fractions is None:
raise Exception("Unroll only works if the composite has defined fractions.")
phases = []
fractions = []
for i, phase in enumerate(self.phases):
p_mineral, p_fraction = phase.unroll()
check_pairs(p_mineral, p_fraction)
fractions.extend([f * self.molar_fractions[i] for f in p_fraction])
phases.extend(p_mineral)
return phases, fractions
| (self) |
10,926 | burnman.classes.composition | Composition |
Class for a composition object, which can be used
to store, modify and renormalize compositions,
and also convert between mass, molar
and atomic amounts. Weight is provided as an alias
for mass, as we assume that only Earthlings
will use this software.
This class is available as ``burnman.Composition``.
| class Composition(object):
"""
Class for a composition object, which can be used
to store, modify and renormalize compositions,
and also convert between mass, molar
and atomic amounts. Weight is provided as an alias
for mass, as we assume that only Earthlings
will use this software.
This class is available as ``burnman.Composition``.
"""
def __init__(self, composition_dictionary, unit_type="mass", normalize=False):
"""
Create a composition using a dictionary and unit type.
:param composition_dictionary: Dictionary of components
(given as a string) and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar' (optional, 'mass' as default)
Specify whether the input composition is given as mass or
molar amounts.
:type unit_type: str
:param normalize: If False, absolute numbers of kilograms/moles of component are
stored, otherwise the component amounts of returned compositions
will sum to one (until Composition.renormalize() is used).
:type normalize: bool
"""
self._cached = {}
n_total = float(sum(composition_dictionary.values()))
# Create the input dictionary, normalize if requested
input_dictionary = OrderedCounter(deepcopy(composition_dictionary))
if normalize:
for k in composition_dictionary.keys():
input_dictionary[k] = composition_dictionary[k] / n_total
# Break component formulae into atomic dictionaries
self.component_formulae = {
c: dictionarize_formula(c) for c in composition_dictionary.keys()
}
# Create lists of elemental compositions of components
self.element_list = OrderedCounter()
for component in self.component_formulae.values():
self.element_list += OrderedCounter(
{element: n_atoms for (element, n_atoms) in component.items()}
)
self.element_list = list(self.element_list.keys())
if unit_type == "mass" or unit_type == "weight":
self.mass_composition = input_dictionary
elif unit_type == "molar":
self.mass_composition = self._mole_to_mass_composition(input_dictionary)
else:
raise Exception(
"Unit type not yet implemented. "
"Should be either mass, weight or molar."
)
def renormalize(self, unit_type, normalization_component, normalization_amount):
"""
Change the total amount of material in the composition
to satisfy a given normalization condition
(mass, weight, molar, or atomic)
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type with which to normalize the composition
:type unit_type: str
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in the composition, or have the value 'total'.
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition.
:type normalization_amount: float
"""
if unit_type not in ["mass", "weight", "molar", "atomic"]:
raise Exception(
"unit_type not yet implemented."
"Should be either mass, weight, molar or atomic."
)
c = self.composition(unit_type)
if normalization_component == "total":
f = normalization_amount / float(sum(c.values()))
else:
f = normalization_amount / c[normalization_component]
new_mass_composition = OrderedCounter()
for k in self.mass_composition.keys():
new_mass_composition[k] = self.mass_composition[k] * f
self.mass_composition = new_mass_composition
def add_components(self, composition_dictionary, unit_type):
"""
Add (or remove) components from the composition.
The components are added to the current state of the
(mass, weight or molar) composition; if the composition has
been renormalised, then this should be taken into account.
:param composition_dictionary: Components to add, and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar'.
Unit type of the components to be added.
:type unit_type: str
"""
if unit_type == "mass" or unit_type == "weight":
composition = self.mass_composition
elif unit_type == "molar":
composition = self.molar_composition
else:
raise Exception(
"Unit type not recognised. " "Should be either mass, weight or molar."
)
composition += OrderedCounter(composition_dictionary)
# Reinitialize composition object
self.__init__(composition, unit_type)
def change_component_set(self, new_component_list):
"""
Change the set of basis components without
changing the bulk composition.
Will raise an exception if the new component set is
invalid for the given composition.
:param new_component_list: New set of basis components.
:type new_component_list: list of strings
"""
composition = np.array(
[self.atomic_composition[element] for element in self.element_list]
)
component_matrix = np.zeros((len(new_component_list), len(self.element_list)))
for i, component in enumerate(new_component_list):
formula = dictionarize_formula(component)
for element, n_atoms in formula.items():
component_matrix[i][self.element_list.index(element)] = n_atoms
sol = nnls(component_matrix.T, composition)
if sol[1] < 1.0e-12:
component_amounts = sol[0]
else:
raise Exception(
"Failed to change component set. "
"Could not find a non-negative "
"least squares solution. "
"Can the bulk composition be described "
"with this set of components?"
)
composition = OrderedCounter(dict(zip(new_component_list, component_amounts)))
# Reinitialize the object
self.__init__(composition, "molar")
def _mole_to_mass_composition(self, molar_comp):
"""
Hidden function to returns the mass composition as a counter [kg]
"""
cf = self.component_formulae
mass_composition = OrderedCounter(
{c: molar_comp[c] * formula_mass(cf[c]) for c in molar_comp.keys()}
)
return mass_composition
@property
def weight_composition(self):
"""
An alias for mass composition [kg].
"""
return self.mass_composition
@property
def molar_composition(self):
"""
Returns the molar composition as a counter [moles]
"""
mass_comp = self.mass_composition
cf = self.component_formulae
return OrderedCounter(
{c: mass_comp[c] / formula_mass(cf[c]) for c in mass_comp.keys()}
)
@property
def atomic_composition(self):
"""
Returns the atomic composition as a counter [moles]
"""
return self._moles_to_atoms(self.molar_composition)
def composition(self, unit_type):
"""
Helper function to return the composition in the
desired type.
:param unit_type: One of 'mass', 'weight', 'molar' and 'atomic'.
:type unit_type: str
:returns: Mass (weight), molar or atomic composition.
:rtype: OrderedCounter
"""
return getattr(self, f"{unit_type}_composition")
def _moles_to_atoms(self, molar_comp_dictionary):
"""
Hidden function that converts a molar component
dictionary into an atomic (elemental) dictionary
"""
component_matrix = np.zeros(
(len(self.component_formulae), len(self.element_list))
)
cf = self.component_formulae
molar_composition_vector = np.zeros(len(cf))
for i, (component, formula) in enumerate(cf.items()):
molar_composition_vector[i] = molar_comp_dictionary[component]
for element, n_atoms in formula.items():
component_matrix[i][self.element_list.index(element)] = n_atoms
atom_compositions = np.dot(molar_composition_vector, component_matrix)
return OrderedCounter(dict(zip(self.element_list, atom_compositions)))
def print(
self,
unit_type,
significant_figures=1,
normalization_component="total",
normalization_amount=None,
):
"""
Pretty-print function for the composition
This does not renormalize the Composition object itself,
only the printed values.
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type in which to print the composition.
:type unit_type: str
:param significant_figures: Number of significant figures
for each amount.
:type significant_figures: int
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in composite, or have the value 'total'.
(default = 'total')
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition. If not explicitly set,
no renormalization will be applied.
:type normalization_amount: float
"""
if unit_type not in ["mass", "weight", "molar", "atomic"]:
raise Exception(
"unit_type not yet implemented."
"Should be either mass, weight, molar or atomic."
)
c = self.composition(unit_type)
print(f"{unit_type.capitalize()} composition")
if normalization_amount is None:
f = 1
elif normalization_component == "total":
f = normalization_amount / float(sum(c.values()))
else:
f = normalization_amount / c[normalization_component]
for key, value in sorted(c.items()):
print(f"{key}: {value*f:0.{significant_figures}f}")
| (composition_dictionary, unit_type='mass', normalize=False) |
10,927 | burnman.classes.composition | __init__ |
Create a composition using a dictionary and unit type.
:param composition_dictionary: Dictionary of components
(given as a string) and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar' (optional, 'mass' as default)
Specify whether the input composition is given as mass or
molar amounts.
:type unit_type: str
:param normalize: If False, absolute numbers of kilograms/moles of component are
stored, otherwise the component amounts of returned compositions
will sum to one (until Composition.renormalize() is used).
:type normalize: bool
| def __init__(self, composition_dictionary, unit_type="mass", normalize=False):
"""
Create a composition using a dictionary and unit type.
:param composition_dictionary: Dictionary of components
(given as a string) and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar' (optional, 'mass' as default)
Specify whether the input composition is given as mass or
molar amounts.
:type unit_type: str
:param normalize: If False, absolute numbers of kilograms/moles of component are
stored, otherwise the component amounts of returned compositions
will sum to one (until Composition.renormalize() is used).
:type normalize: bool
"""
self._cached = {}
n_total = float(sum(composition_dictionary.values()))
# Create the input dictionary, normalize if requested
input_dictionary = OrderedCounter(deepcopy(composition_dictionary))
if normalize:
for k in composition_dictionary.keys():
input_dictionary[k] = composition_dictionary[k] / n_total
# Break component formulae into atomic dictionaries
self.component_formulae = {
c: dictionarize_formula(c) for c in composition_dictionary.keys()
}
# Create lists of elemental compositions of components
self.element_list = OrderedCounter()
for component in self.component_formulae.values():
self.element_list += OrderedCounter(
{element: n_atoms for (element, n_atoms) in component.items()}
)
self.element_list = list(self.element_list.keys())
if unit_type == "mass" or unit_type == "weight":
self.mass_composition = input_dictionary
elif unit_type == "molar":
self.mass_composition = self._mole_to_mass_composition(input_dictionary)
else:
raise Exception(
"Unit type not yet implemented. "
"Should be either mass, weight or molar."
)
| (self, composition_dictionary, unit_type='mass', normalize=False) |
10,928 | burnman.classes.composition | _mole_to_mass_composition |
Hidden function to returns the mass composition as a counter [kg]
| def _mole_to_mass_composition(self, molar_comp):
"""
Hidden function to returns the mass composition as a counter [kg]
"""
cf = self.component_formulae
mass_composition = OrderedCounter(
{c: molar_comp[c] * formula_mass(cf[c]) for c in molar_comp.keys()}
)
return mass_composition
| (self, molar_comp) |
10,929 | burnman.classes.composition | _moles_to_atoms |
Hidden function that converts a molar component
dictionary into an atomic (elemental) dictionary
| def _moles_to_atoms(self, molar_comp_dictionary):
"""
Hidden function that converts a molar component
dictionary into an atomic (elemental) dictionary
"""
component_matrix = np.zeros(
(len(self.component_formulae), len(self.element_list))
)
cf = self.component_formulae
molar_composition_vector = np.zeros(len(cf))
for i, (component, formula) in enumerate(cf.items()):
molar_composition_vector[i] = molar_comp_dictionary[component]
for element, n_atoms in formula.items():
component_matrix[i][self.element_list.index(element)] = n_atoms
atom_compositions = np.dot(molar_composition_vector, component_matrix)
return OrderedCounter(dict(zip(self.element_list, atom_compositions)))
| (self, molar_comp_dictionary) |
10,930 | burnman.classes.composition | add_components |
Add (or remove) components from the composition.
The components are added to the current state of the
(mass, weight or molar) composition; if the composition has
been renormalised, then this should be taken into account.
:param composition_dictionary: Components to add, and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar'.
Unit type of the components to be added.
:type unit_type: str
| def add_components(self, composition_dictionary, unit_type):
"""
Add (or remove) components from the composition.
The components are added to the current state of the
(mass, weight or molar) composition; if the composition has
been renormalised, then this should be taken into account.
:param composition_dictionary: Components to add, and their amounts.
:type composition_dictionary: dictionary
:param unit_type: 'mass', 'weight' or 'molar'.
Unit type of the components to be added.
:type unit_type: str
"""
if unit_type == "mass" or unit_type == "weight":
composition = self.mass_composition
elif unit_type == "molar":
composition = self.molar_composition
else:
raise Exception(
"Unit type not recognised. " "Should be either mass, weight or molar."
)
composition += OrderedCounter(composition_dictionary)
# Reinitialize composition object
self.__init__(composition, unit_type)
| (self, composition_dictionary, unit_type) |
10,931 | burnman.classes.composition | change_component_set |
Change the set of basis components without
changing the bulk composition.
Will raise an exception if the new component set is
invalid for the given composition.
:param new_component_list: New set of basis components.
:type new_component_list: list of strings
| def change_component_set(self, new_component_list):
"""
Change the set of basis components without
changing the bulk composition.
Will raise an exception if the new component set is
invalid for the given composition.
:param new_component_list: New set of basis components.
:type new_component_list: list of strings
"""
composition = np.array(
[self.atomic_composition[element] for element in self.element_list]
)
component_matrix = np.zeros((len(new_component_list), len(self.element_list)))
for i, component in enumerate(new_component_list):
formula = dictionarize_formula(component)
for element, n_atoms in formula.items():
component_matrix[i][self.element_list.index(element)] = n_atoms
sol = nnls(component_matrix.T, composition)
if sol[1] < 1.0e-12:
component_amounts = sol[0]
else:
raise Exception(
"Failed to change component set. "
"Could not find a non-negative "
"least squares solution. "
"Can the bulk composition be described "
"with this set of components?"
)
composition = OrderedCounter(dict(zip(new_component_list, component_amounts)))
# Reinitialize the object
self.__init__(composition, "molar")
| (self, new_component_list) |
10,932 | burnman.classes.composition | composition |
Helper function to return the composition in the
desired type.
:param unit_type: One of 'mass', 'weight', 'molar' and 'atomic'.
:type unit_type: str
:returns: Mass (weight), molar or atomic composition.
:rtype: OrderedCounter
| def composition(self, unit_type):
"""
Helper function to return the composition in the
desired type.
:param unit_type: One of 'mass', 'weight', 'molar' and 'atomic'.
:type unit_type: str
:returns: Mass (weight), molar or atomic composition.
:rtype: OrderedCounter
"""
return getattr(self, f"{unit_type}_composition")
| (self, unit_type) |
10,933 | burnman.classes.composition | print |
Pretty-print function for the composition
This does not renormalize the Composition object itself,
only the printed values.
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type in which to print the composition.
:type unit_type: str
:param significant_figures: Number of significant figures
for each amount.
:type significant_figures: int
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in composite, or have the value 'total'.
(default = 'total')
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition. If not explicitly set,
no renormalization will be applied.
:type normalization_amount: float
| def print(
self,
unit_type,
significant_figures=1,
normalization_component="total",
normalization_amount=None,
):
"""
Pretty-print function for the composition
This does not renormalize the Composition object itself,
only the printed values.
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type in which to print the composition.
:type unit_type: str
:param significant_figures: Number of significant figures
for each amount.
:type significant_figures: int
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in composite, or have the value 'total'.
(default = 'total')
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition. If not explicitly set,
no renormalization will be applied.
:type normalization_amount: float
"""
if unit_type not in ["mass", "weight", "molar", "atomic"]:
raise Exception(
"unit_type not yet implemented."
"Should be either mass, weight, molar or atomic."
)
c = self.composition(unit_type)
print(f"{unit_type.capitalize()} composition")
if normalization_amount is None:
f = 1
elif normalization_component == "total":
f = normalization_amount / float(sum(c.values()))
else:
f = normalization_amount / c[normalization_component]
for key, value in sorted(c.items()):
print(f"{key}: {value*f:0.{significant_figures}f}")
| (self, unit_type, significant_figures=1, normalization_component='total', normalization_amount=None) |
10,934 | burnman.classes.composition | renormalize |
Change the total amount of material in the composition
to satisfy a given normalization condition
(mass, weight, molar, or atomic)
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type with which to normalize the composition
:type unit_type: str
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in the composition, or have the value 'total'.
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition.
:type normalization_amount: float
| def renormalize(self, unit_type, normalization_component, normalization_amount):
"""
Change the total amount of material in the composition
to satisfy a given normalization condition
(mass, weight, molar, or atomic)
:param unit_type: 'mass', 'weight', 'molar' or 'atomic'
Unit type with which to normalize the composition
:type unit_type: str
:param normalization_component: Component/element on which to renormalize.
String must either be one of the components/elements
already in the composition, or have the value 'total'.
:type normalization_component: str
:param normalization_amount: Amount of component in the
renormalised composition.
:type normalization_amount: float
"""
if unit_type not in ["mass", "weight", "molar", "atomic"]:
raise Exception(
"unit_type not yet implemented."
"Should be either mass, weight, molar or atomic."
)
c = self.composition(unit_type)
if normalization_component == "total":
f = normalization_amount / float(sum(c.values()))
else:
f = normalization_amount / c[normalization_component]
new_mass_composition = OrderedCounter()
for k in self.mass_composition.keys():
new_mass_composition[k] = self.mass_composition[k] * f
self.mass_composition = new_mass_composition
| (self, unit_type, normalization_component, normalization_amount) |
10,935 | burnman.classes.elasticsolution | ElasticSolution |
This is the base class for all Elastic solutions.
Site occupancies, endmember activities and the constant
and volume and temperature dependencies of the excess
properties can be queried after using set_composition().
States of the solution can only be queried after setting
the pressure, temperature and composition using set_state()
and set_composition.
This class is available as :class:`burnman.ElasticSolution`.
It uses an instance of :class:`burnman.ElasticSolutionModel` to
calculate interaction terms between endmembers.
All the solution parameters are expected to be in SI units. This
means that the interaction parameters should be in J/mol, with the T
and V derivatives in J/K/mol and Pa/mol.
The parameters are relevant to all Elastic solution models. Please
see the documentation for individual models for details about
other parameters.
:param name: Name of the solution.
:type name: string
:param solution_model: The ElasticSolutionModel object defining the
properties of the solution.
:type solution_model: :class:`burnman.ElasticSolutionModel`
:param molar_fractions: The molar fractions of each endmember in the solution.
Can be reset using the set_composition() method.
:type molar_fractions: numpy.array
| class ElasticSolution(Mineral):
"""
This is the base class for all Elastic solutions.
Site occupancies, endmember activities and the constant
and volume and temperature dependencies of the excess
properties can be queried after using set_composition().
States of the solution can only be queried after setting
the pressure, temperature and composition using set_state()
and set_composition.
This class is available as :class:`burnman.ElasticSolution`.
It uses an instance of :class:`burnman.ElasticSolutionModel` to
calculate interaction terms between endmembers.
All the solution parameters are expected to be in SI units. This
means that the interaction parameters should be in J/mol, with the T
and V derivatives in J/K/mol and Pa/mol.
The parameters are relevant to all Elastic solution models. Please
see the documentation for individual models for details about
other parameters.
:param name: Name of the solution.
:type name: string
:param solution_model: The ElasticSolutionModel object defining the
properties of the solution.
:type solution_model: :class:`burnman.ElasticSolutionModel`
:param molar_fractions: The molar fractions of each endmember in the solution.
Can be reset using the set_composition() method.
:type molar_fractions: numpy.array
"""
def __init__(self, name=None, solution_model=None, molar_fractions=None):
"""
Set up matrices to speed up calculations for when P, T, X is defined.
"""
Mineral.__init__(self)
# Solution needs a method attribute to call Mineral.set_state().
# Note that set_method() below will not change self.method
self.method = "ElasticSolutionMethod"
if name is not None:
self.name = name
if solution_model is not None:
self.solution_model = solution_model
if isinstance(solution_model, ElasticMechanicalSolution):
self.solution_type = "mechanical"
else:
self.solution_type = "chemical"
# Starting guess and delta for pressure iteration
self.min_V0 = min(
[mbr[0].params["V_0"] for mbr in self.solution_model.endmembers]
)
self.dV = 0.01 * self.min_V0
# Equation of state
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(
self.solution_model.endmembers[i][0].params["equation_of_state"]
)
# Molar fractions
if molar_fractions is not None:
self.set_composition(molar_fractions)
@cached_property
def endmembers(self):
return self.solution_model.endmembers
def set_composition(self, molar_fractions):
"""
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember,
needs to sum to one.
:type molar_fractions: list of float
"""
assert len(self.solution_model.endmembers) == len(molar_fractions)
if self.solution_type != "mechanical":
assert sum(molar_fractions) > 0.9999
assert sum(molar_fractions) < 1.0001
self.reset()
self.molar_fractions = np.array(molar_fractions)
if self.temperature is not None:
_ = self.molar_volume
def set_method(self, method):
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(method)
# note: do not set self.method here!
self.reset()
def set_state(self, pressure, temperature):
Mineral.set_state(self, pressure, temperature)
try:
_ = self.molar_volume
except AttributeError:
pass
@material_property
def formula(self):
"""
Returns molar chemical formula of the solution.
"""
return sum_formulae(self.endmember_formulae, self.molar_fractions)
@material_property
def activities(self):
"""
Returns a list of endmember activities [unitless].
"""
volumes = [
self.solution_model.endmembers[i][0].method.volume(
self.pressure,
self.temperature,
self.solution_model.endmembers[i][0].params,
)
for i in range(self.n_endmembers)
]
gibbs_pure = [
self.solution_model.endmembers[i][0].method.gibbs_free_energy(
self.pressure,
self.temperature,
volumes[i],
self.solution_model.endmembers[i][0].params,
)
for i in range(self.n_endmembers)
]
acts = np.exp(
(self.partial_gibbs - np.array(gibbs_pure))
/ (gas_constant * self.temperature)
)
return acts
@material_property
def activity_coefficients(self):
"""
Returns a list of endmember activity coefficients
(gamma = activity / ideal activity) [unitless].
"""
return np.exp(
np.log(self.activities)
- IdealSolution._log_ideal_activities(
self.solution_model, self.molar_fractions
)
)
@material_property
def molar_internal_energy(self):
"""
Returns molar internal energy of the mineral [J/mol].
Aliased with self.energy
"""
return self.molar_helmholtz + self.temperature * self.molar_entropy
@material_property
def _excess_partial_helmholtz(self):
"""
Returns excess partial molar helmholtz energy
at constant volume [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_partial_helmholtz_energies(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _excess_partial_pressures(self):
"""
Returns excess partial pressures at constant volume [Pa].
Property specific to solutions.
"""
return self.solution_model.excess_partial_pressures(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _excess_partial_entropies(self):
"""
Returns excess partial entropies at constant volume [J/K].
Property specific to solutions.
"""
return self.solution_model.excess_partial_entropies(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _partial_helmholtz(self):
"""
Returns endmember partial molar Helmholtz energy at constant volume [J/mol].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].helmholtz
for i in range(self.n_endmembers)
]
)
+ self._excess_partial_helmholtz
)
@material_property
def _partial_pressures(self):
"""
Returns endmember partial pressures at constant volume [Pa].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].pressure
for i in range(self.n_endmembers)
]
)
+ self._excess_partial_pressures
)
@material_property
def _partial_entropies(self):
"""
Returns endmember partial entropies at constant volume [J/K].
Property specific to solutions.
"""
return (
np.array(
[
self.solution_model.endmembers[i][0].molar_entropy
for i in range(self.n_endmembers)
]
)
+ self._excess_partial_entropies
)
@material_property
def partial_gibbs(self):
"""
Returns endmember partial molar Gibbs energy
at constant pressure [J/mol].
Property specific to solutions.
"""
return self._partial_helmholtz + self.pressure * self.molar_volume
@material_property
def _dPdX(self):
"""
Returns the change in pressure with amount of each endmember
at constant volume.
"""
sumX = np.sum(self.molar_fractions)
sumXP = np.einsum("i,i->", self.molar_fractions, self._partial_pressures)
return (self._partial_pressures * sumX - sumXP) / (sumX * sumX)
@material_property
def _dVdX(self):
"""
Returns the change in pressure with amount of each endmember
at constant pressure.
"""
return self.molar_volume / self.isothermal_bulk_modulus * self._dPdX
@material_property
def _dSdX_mod(self):
"""
Returns the additional change in entropy with
amount of each endmember due to converting from constant volume
to constant pressure
"""
return self.alpha * self.molar_volume * self._dPdX
@material_property
def partial_volumes(self):
"""
Returns endmember partial molar volumes [m^3/mol].
Property specific to solutions.
"""
A = np.eye(self.n_endmembers) - self.molar_fractions
Vs = self.molar_volume + np.einsum("ij, j->i", A, self._dVdX)
return Vs
@material_property
def partial_entropies(self):
"""
Returns endmember partial molar entropies [J/K/mol].
Property specific to solutions.
"""
A = np.eye(self.n_endmembers) - self.molar_fractions
Ss = self._partial_entropies + np.einsum("ij, j->i", A, self._dSdX_mod)
return Ss
@material_property
def _excess_helmholtz(self):
"""
Returns molar excess Helmholtz energy at constant volume [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_helmholtz_energy(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _helmholtz_hessian(self):
"""
Returns an array containing the second compositional derivative
of the Helmholtz energy at constant volume [J/mol].
Property specific to solutions.
"""
return self.solution_model.helmholtz_hessian(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _entropy_hessian(self):
"""
Returns an array containing the second compositional derivative
of the entropy at constant volume [J/K].
Property specific to solutions.
"""
return self.solution_model.entropy_hessian(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def _pressure_hessian(self):
"""
Returns an array containing the second compositional derivative
of the pressure at constant volume [Pa].
Property specific to solutions.
"""
return self.solution_model.pressure_hessian(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def gibbs_hessian(self):
"""
Returns an array containing the second compositional derivative
of the Gibbs energy at constant pressure [J/mol].
Property specific to solutions.
"""
raise NotImplementedError
@material_property
def molar_helmholtz(self):
"""
Returns molar Helmholtz energy of the solution [J/mol].
Aliased with self.helmholtz.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].molar_helmholtz
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self._excess_helmholtz
)
@material_property
def molar_gibbs(self):
"""
Returns molar Gibbs free energy of the solution [J/mol].
Aliased with self.gibbs.
"""
return self.molar_helmholtz + self.pressure * self.molar_volume
@material_property
def molar_mass(self):
"""
Returns molar mass of the solution [kg/mol].
"""
return sum(
[
self.solution_model.endmembers[i][0].molar_mass
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
@material_property
def excess_pressure(self):
"""
Returns excess pressure of the solution [Pa].
Specific property for solutions.
"""
return self.solution_model.excess_pressure(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def molar_volume(self):
"""
Returns molar volume of the solution [m^3/mol].
Aliased with self.V.
"""
def _delta_pressure(volume):
self._ptmp = [
self.solution_model.endmembers[i][0].method.pressure(
self.temperature,
volume,
self.solution_model.endmembers[i][0].params,
)
for i in range(self.n_endmembers)
]
pressure_try = sum(
[
self._ptmp[i] * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
) + self.solution_model.excess_pressure(
volume, self.temperature, self.molar_fractions
)
return pressure_try - self.pressure
def _K_T(volume):
# Note, this only works when the excess pressure is not a function
# of V or T.
return sum(
[
self.solution_model.endmembers[i][0].method.isothermal_bulk_modulus(
0.0,
self.temperature,
volume,
self.solution_model.endmembers[i][0].params,
)
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
try:
# The first attempt to find a bracket for
# root finding uses V_0 as a starting point
sol = bracket(_delta_pressure, self.min_V0, self.dV)
except Exception:
# At high temperature, the naive bracketing above may
# try a volume guess that exceeds the point at which the
# bulk modulus goes negative at that temperature.
# In this case, we try a more nuanced approach by
# first finding the volume at which the bulk modulus goes
# negative, and then either (a) raising an exception if the
# desired pressure is less than the pressure at that volume,
# or (b) using that pressure to create a better bracket for
# brentq.
sol_K_T = bracket(_K_T, self.min_V0, self.dV)
V_crit = opt.brentq(_K_T, sol_K_T[0], sol_K_T[1])
P_min = self.pressure + _delta_pressure(V_crit)
if P_min > self.pressure:
raise Exception(
"The desired pressure is not achievable "
"at this temperature. The minimum pressure "
f"achievable is {P_min:.2e} Pa."
)
else:
try:
sol = bracket(_delta_pressure, V_crit - self.dV, self.dV)
except Exception:
raise Exception(
"Cannot find a volume, perhaps you are "
"outside of the range of validity for "
"the equation of state?"
)
V = opt.brentq(_delta_pressure, sol[0], sol[1])
_delta_pressure(V)
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_state(
self._ptmp[i], self.temperature
)
return V
@material_property
def density(self):
"""
Returns density of the solution [kg/m^3].
Aliased with self.rho.
"""
return self.molar_mass / self.molar_volume
@material_property
def excess_entropy(self):
"""
Returns excess molar entropy [J/K/mol].
Property specific to solutions.
"""
return self.solution_model.excess_entropy(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def molar_entropy(self):
"""
Returns molar entropy of the solution [J/K/mol].
Aliased with self.S.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].S * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_entropy
)
@material_property
def excess_enthalpy(self):
"""
Returns excess molar enthalpy [J/mol].
Property specific to solutions.
"""
return self.solution_model.excess_enthalpy(
self.molar_volume, self.temperature, self.molar_fractions
)
@material_property
def molar_enthalpy(self):
"""
Returns molar enthalpy of the solution [J/mol].
Aliased with self.H.
"""
return (
sum(
[
self.solution_model.endmembers[i][0].H * self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
+ self.excess_enthalpy
)
@material_property
def isothermal_bulk_modulus(self):
"""
Returns isothermal bulk modulus of the solution [Pa].
Aliased with self.K_T.
"""
return sum(
[
self.solution_model.endmembers[i][0].isothermal_bulk_modulus
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
@material_property
def adiabatic_bulk_modulus(self):
"""
Returns adiabatic bulk modulus of the solution [Pa].
Aliased with self.K_S.
"""
if self.temperature < 1e-10:
return self.isothermal_bulk_modulus
else:
return (
self.isothermal_bulk_modulus
* self.molar_heat_capacity_p
/ self.molar_heat_capacity_v
)
@material_property
def isothermal_compressibility(self):
"""
Returns isothermal compressibility of the solution.
(or inverse isothermal bulk modulus) [1/Pa].
Aliased with self.K_T.
"""
return 1.0 / self.isothermal_bulk_modulus
@material_property
def adiabatic_compressibility(self):
"""
Returns adiabatic compressibility of the solution.
(or inverse adiabatic bulk modulus) [1/Pa].
Aliased with self.K_S.
"""
return 1.0 / self.adiabatic_bulk_modulus
@material_property
def shear_modulus(self):
"""
Returns shear modulus of the solution [Pa].
Aliased with self.G.
"""
G_list = np.fromiter(
(e[0].G for e in self.solution_model.endmembers),
dtype=float,
count=self.n_endmembers,
)
return reuss_average_function(self.molar_fractions, G_list)
@material_property
def p_wave_velocity(self):
"""
Returns P wave speed of the solution [m/s].
Aliased with self.v_p.
"""
return np.sqrt(
(self.adiabatic_bulk_modulus + 4.0 / 3.0 * self.shear_modulus)
/ self.density
)
@material_property
def bulk_sound_velocity(self):
"""
Returns bulk sound speed of the solution [m/s].
Aliased with self.v_phi.
"""
return np.sqrt(self.adiabatic_bulk_modulus / self.density)
@material_property
def shear_wave_velocity(self):
"""
Returns shear wave speed of the solution [m/s].
Aliased with self.v_s.
"""
return np.sqrt(self.shear_modulus / self.density)
@material_property
def grueneisen_parameter(self):
"""
Returns grueneisen parameter of the solution [unitless].
Aliased with self.gr.
"""
if self.temperature < 1e-10:
return float("nan")
else:
return (
self.thermal_expansivity
* self.isothermal_bulk_modulus
* self.molar_volume
/ self.molar_heat_capacity_v
)
@material_property
def thermal_expansivity(self):
"""
Returns thermal expansion coefficient (alpha)
of the solution [1/K].
Aliased with self.alpha.
"""
alphaKT = sum(
[
self.solution_model.endmembers[i][0].isothermal_bulk_modulus
* self.solution_model.endmembers[i][0].alpha
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
return alphaKT / self.isothermal_bulk_modulus
@material_property
def molar_heat_capacity_v(self):
"""
Returns molar heat capacity at constant volume of the
solution [J/K/mol].
Aliased with self.C_v.
"""
return sum(
[
self.solution_model.endmembers[i][0].molar_heat_capacity_v
* self.molar_fractions[i]
for i in range(self.n_endmembers)
]
)
@material_property
def molar_heat_capacity_p(self):
"""
Returns molar heat capacity at constant pressure
of the solution [J/K/mol].
Aliased with self.C_p.
"""
return (
self.molar_heat_capacity_v
+ self.molar_volume
* self.temperature
* self.thermal_expansivity
* self.thermal_expansivity
* self.isothermal_bulk_modulus
)
@cached_property
def stoichiometric_matrix(self):
"""
A sympy Matrix where each element M[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
def f(i, j):
e = self.elements[j]
if e in self.endmember_formulae[i]:
return nsimplify(self.endmember_formulae[i][e])
else:
return 0
return Matrix(len(self.endmember_formulae), len(self.elements), f)
@cached_property
def stoichiometric_array(self):
"""
An array where each element arr[i,j] corresponds
to the number of atoms of element[j] in endmember[i].
"""
return np.array(self.stoichiometric_matrix)
@cached_property
def reaction_basis(self):
"""
An array where each element arr[i,j] corresponds
to the number of moles of endmember[j] involved in reaction[i].
"""
reaction_basis = np.array(
[v[:] for v in self.stoichiometric_matrix.T.nullspace()]
)
if len(reaction_basis) == 0:
reaction_basis = np.empty((0, len(self.endmember_names)))
return reaction_basis
@cached_property
def n_reactions(self):
"""
The number of reactions in reaction_basis.
"""
return len(self.reaction_basis[:, 0])
@cached_property
def independent_element_indices(self):
"""
A list of an independent set of element indices. If the amounts of
these elements are known (element_amounts),
the amounts of the other elements can be inferred by
-compositional_null_basis[independent_element_indices].dot(element_amounts).
"""
return sorted(independent_row_indices(self.stoichiometric_matrix.T))
@cached_property
def dependent_element_indices(self):
"""
The element indices not included in the independent list.
"""
return [
i
for i in range(len(self.elements))
if i not in self.independent_element_indices
]
@cached_property
def compositional_null_basis(self):
"""
An array N such that N.b = 0 for all bulk compositions that can
be produced with a linear sum of the endmembers in the solution.
"""
null_basis = np.array([v[:] for v in self.stoichiometric_matrix.nullspace()])
M = null_basis[:, self.dependent_element_indices]
assert (M.shape[0] == M.shape[1]) and (M == np.eye(M.shape[0])).all()
return null_basis
@cached_property
def endmember_formulae(self):
"""
A list of formulae for all the endmember in the solution.
"""
return [mbr[0].params["formula"] for mbr in self.solution_model.endmembers]
@cached_property
def endmember_names(self):
"""
A list of names for all the endmember in the solution.
"""
return [mbr[0].name for mbr in self.solution_model.endmembers]
@cached_property
def n_endmembers(self):
"""
The number of endmembers in the solution.
"""
return len(self.solution_model.endmembers)
@cached_property
def elements(self):
"""
A list of the elements which could be contained in the solution,
returned in the IUPAC element order.
"""
keys = []
for f in self.endmember_formulae:
keys.extend(f.keys())
return sort_element_list_to_IUPAC_order(set(keys))
| (name=None, solution_model=None, molar_fractions=None) |
10,936 | burnman.classes.elasticsolution | __init__ |
Set up matrices to speed up calculations for when P, T, X is defined.
| def __init__(self, name=None, solution_model=None, molar_fractions=None):
"""
Set up matrices to speed up calculations for when P, T, X is defined.
"""
Mineral.__init__(self)
# Solution needs a method attribute to call Mineral.set_state().
# Note that set_method() below will not change self.method
self.method = "ElasticSolutionMethod"
if name is not None:
self.name = name
if solution_model is not None:
self.solution_model = solution_model
if isinstance(solution_model, ElasticMechanicalSolution):
self.solution_type = "mechanical"
else:
self.solution_type = "chemical"
# Starting guess and delta for pressure iteration
self.min_V0 = min(
[mbr[0].params["V_0"] for mbr in self.solution_model.endmembers]
)
self.dV = 0.01 * self.min_V0
# Equation of state
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(
self.solution_model.endmembers[i][0].params["equation_of_state"]
)
# Molar fractions
if molar_fractions is not None:
self.set_composition(molar_fractions)
| (self, name=None, solution_model=None, molar_fractions=None) |
10,942 | burnman.classes.elasticsolution | set_composition |
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember,
needs to sum to one.
:type molar_fractions: list of float
| def set_composition(self, molar_fractions):
"""
Set the composition for this solution.
Resets cached properties.
:param molar_fractions: Molar abundance for each endmember,
needs to sum to one.
:type molar_fractions: list of float
"""
assert len(self.solution_model.endmembers) == len(molar_fractions)
if self.solution_type != "mechanical":
assert sum(molar_fractions) > 0.9999
assert sum(molar_fractions) < 1.0001
self.reset()
self.molar_fractions = np.array(molar_fractions)
if self.temperature is not None:
_ = self.molar_volume
| (self, molar_fractions) |
10,943 | burnman.classes.elasticsolution | set_method | null | def set_method(self, method):
for i in range(self.n_endmembers):
self.solution_model.endmembers[i][0].set_method(method)
# note: do not set self.method here!
self.reset()
| (self, method) |
10,944 | burnman.classes.elasticsolution | set_state | null | def set_state(self, pressure, temperature):
Mineral.set_state(self, pressure, temperature)
try:
_ = self.molar_volume
except AttributeError:
pass
| (self, pressure, temperature) |
10,961 | burnman.classes.elasticsolutionmodel | ElasticSolutionModel |
This is the base class for an Elastic solution model, intended for use
in defining solutions and performing thermodynamic calculations
on them. All minerals of type :class:`burnman.Solution` use
a solution model for defining how the endmembers in the solution
interact.
A user wanting a new solution model should define the functions included
in the base class. All of the functions in the base class return zero,
so if the user-defined solution model does not implement them,
they essentially have no effect, and the Helmholtz energy and
pressure of a solution will be equal to the weighted arithmetic
averages of the different endmember values.
| class ElasticSolutionModel(object):
"""
This is the base class for an Elastic solution model, intended for use
in defining solutions and performing thermodynamic calculations
on them. All minerals of type :class:`burnman.Solution` use
a solution model for defining how the endmembers in the solution
interact.
A user wanting a new solution model should define the functions included
in the base class. All of the functions in the base class return zero,
so if the user-defined solution model does not implement them,
they essentially have no effect, and the Helmholtz energy and
pressure of a solution will be equal to the weighted arithmetic
averages of the different endmember values.
"""
def __init__(self):
"""
Does nothing.
"""
pass
def excess_helmholtz_energy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess Helmholtz free energy of the solution.
The base class implementation assumes that the excess Helmholtz
energy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy.
:rtype: float
"""
return np.dot(
np.array(molar_fractions),
self.excess_partial_helmholtz_energies(
volume, temperature, molar_fractions
),
)
def excess_pressure(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess pressure of the solution.
The base class implementation assumes that the excess pressure is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of the solution.
:rtype: float
"""
return np.dot(
molar_fractions,
self.excess_partial_pressures(volume, temperature, molar_fractions),
)
def excess_entropy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess entropy of the solution.
The base class implementation assumes that the excess entropy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of the solution.
:rtype: float
"""
return np.dot(
molar_fractions,
self.excess_partial_entropies(volume, temperature, molar_fractions),
)
def excess_enthalpy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess enthalpy of the solution.
The base class implementation assumes that the excess enthalpy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess enthalpy of the solution.
:rtype: float
"""
return (
self.excess_helmholtz_energy(volume, temperature, molar_fractions)
+ temperature * self.excess_entropy(volume, temperature, molar_fractions)
- volume * self.excess_pressure(volume, temperature, molar_fractions)
)
def excess_partial_helmholtz_energies(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess Helmholtz energy for each endmember of the solution.
The base class implementation assumes that the excess Helmholtz energy
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy of each endmember
:rtype: numpy.array
"""
return np.zeros_like(molar_fractions)
def excess_partial_entropies(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess entropy for each endmember of the solution.
The base class implementation assumes that the excess entropy
is zero (true for mechanical solutions).
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of each endmember.
:rtype: numpy.array
"""
return np.zeros_like(molar_fractions)
def excess_partial_pressures(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess pressure for each endmember of the solution.
The base class implementation assumes that the excess pressure
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of each endmember.
:rtype: numpy.array
"""
return np.zeros_like(np.array(molar_fractions))
| () |
10,962 | burnman.classes.elasticsolutionmodel | __init__ |
Does nothing.
| def __init__(self):
"""
Does nothing.
"""
pass
| (self) |
10,963 | burnman.classes.elasticsolutionmodel | excess_enthalpy |
Given a list of molar fractions of different phases,
compute the excess enthalpy of the solution.
The base class implementation assumes that the excess enthalpy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess enthalpy of the solution.
:rtype: float
| def excess_enthalpy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess enthalpy of the solution.
The base class implementation assumes that the excess enthalpy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess enthalpy of the solution.
:rtype: float
"""
return (
self.excess_helmholtz_energy(volume, temperature, molar_fractions)
+ temperature * self.excess_entropy(volume, temperature, molar_fractions)
- volume * self.excess_pressure(volume, temperature, molar_fractions)
)
| (self, volume, temperature, molar_fractions) |
10,964 | burnman.classes.elasticsolutionmodel | excess_entropy |
Given a list of molar fractions of different phases,
compute the excess entropy of the solution.
The base class implementation assumes that the excess entropy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of the solution.
:rtype: float
| def excess_entropy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess entropy of the solution.
The base class implementation assumes that the excess entropy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of the solution.
:rtype: float
"""
return np.dot(
molar_fractions,
self.excess_partial_entropies(volume, temperature, molar_fractions),
)
| (self, volume, temperature, molar_fractions) |
10,965 | burnman.classes.elasticsolutionmodel | excess_helmholtz_energy |
Given a list of molar fractions of different phases,
compute the excess Helmholtz free energy of the solution.
The base class implementation assumes that the excess Helmholtz
energy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy.
:rtype: float
| def excess_helmholtz_energy(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess Helmholtz free energy of the solution.
The base class implementation assumes that the excess Helmholtz
energy is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy.
:rtype: float
"""
return np.dot(
np.array(molar_fractions),
self.excess_partial_helmholtz_energies(
volume, temperature, molar_fractions
),
)
| (self, volume, temperature, molar_fractions) |
10,966 | burnman.classes.elasticsolutionmodel | excess_partial_entropies |
Given a list of molar fractions of different phases,
compute the excess entropy for each endmember of the solution.
The base class implementation assumes that the excess entropy
is zero (true for mechanical solutions).
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of each endmember.
:rtype: numpy.array
| def excess_partial_entropies(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess entropy for each endmember of the solution.
The base class implementation assumes that the excess entropy
is zero (true for mechanical solutions).
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess entropy of each endmember.
:rtype: numpy.array
"""
return np.zeros_like(molar_fractions)
| (self, volume, temperature, molar_fractions) |
10,967 | burnman.classes.elasticsolutionmodel | excess_partial_helmholtz_energies |
Given a list of molar fractions of different phases,
compute the excess Helmholtz energy for each endmember of the solution.
The base class implementation assumes that the excess Helmholtz energy
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy of each endmember
:rtype: numpy.array
| def excess_partial_helmholtz_energies(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess Helmholtz energy for each endmember of the solution.
The base class implementation assumes that the excess Helmholtz energy
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess Helmholtz energy of each endmember
:rtype: numpy.array
"""
return np.zeros_like(molar_fractions)
| (self, volume, temperature, molar_fractions) |
10,968 | burnman.classes.elasticsolutionmodel | excess_partial_pressures |
Given a list of molar fractions of different phases,
compute the excess pressure for each endmember of the solution.
The base class implementation assumes that the excess pressure
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of each endmember.
:rtype: numpy.array
| def excess_partial_pressures(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess pressure for each endmember of the solution.
The base class implementation assumes that the excess pressure
is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of each endmember.
:rtype: numpy.array
"""
return np.zeros_like(np.array(molar_fractions))
| (self, volume, temperature, molar_fractions) |
10,969 | burnman.classes.elasticsolutionmodel | excess_pressure |
Given a list of molar fractions of different phases,
compute the excess pressure of the solution.
The base class implementation assumes that the excess pressure is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of the solution.
:rtype: float
| def excess_pressure(self, volume, temperature, molar_fractions):
"""
Given a list of molar fractions of different phases,
compute the excess pressure of the solution.
The base class implementation assumes that the excess pressure is zero.
:param volume: Volume at which to evaluate the solution model. [m^3/mol]
:type volume: float
:param temperature: Temperature at which to evaluate the solution. [K]
:type temperature: float
:param molar_fractions: List of molar fractions of the different
endmembers in solution.
:type molar_fractions: list of floats
:returns: The excess pressure of the solution.
:rtype: float
"""
return np.dot(
molar_fractions,
self.excess_partial_pressures(volume, temperature, molar_fractions),
)
| (self, volume, temperature, molar_fractions) |
10,970 | burnman.classes.mineral_helpers | HelperLowHighPressureRockTransition |
A Helper that represents a Material that switches between two given rocks based
on a given transition pressure.
| class HelperLowHighPressureRockTransition(HelperRockSwitcher):
"""
A Helper that represents a Material that switches between two given rocks based
on a given transition pressure.
"""
def __init__(self, transition_pressure, low_pressure_rock, high_pressure_rock):
self.transition_pressure = transition_pressure
self.rocks = [low_pressure_rock, high_pressure_rock]
HelperRockSwitcher.__init__(self)
self._name = (
"HelperLowHighPressureRockTransition("
+ str(self.transition_pressure)
+ " GPa, "
+ self.rocks[0].name
+ ", "
+ self.rocks[1].name
+ ")"
)
def select_rock(self):
if self._pressure < self.transition_pressure:
return self.rocks[0]
else:
return self.rocks[1]
def set_method(self, method):
for r in self.rocks:
r.set_method(method)
def debug_print(self, indent=""):
print(
"%sHelperLowHighPressureRockTransition (%f GPa):"
% (indent, self.transition_pressure)
)
indent += " "
for r in self.rocks:
r.debug_print(indent)
| (transition_pressure, low_pressure_rock, high_pressure_rock) |
10,971 | burnman.classes.mineral_helpers | __init__ | null | def __init__(self, transition_pressure, low_pressure_rock, high_pressure_rock):
self.transition_pressure = transition_pressure
self.rocks = [low_pressure_rock, high_pressure_rock]
HelperRockSwitcher.__init__(self)
self._name = (
"HelperLowHighPressureRockTransition("
+ str(self.transition_pressure)
+ " GPa, "
+ self.rocks[0].name
+ ", "
+ self.rocks[1].name
+ ")"
)
| (self, transition_pressure, low_pressure_rock, high_pressure_rock) |
10,973 | burnman.classes.mineral_helpers | debug_print | null | def debug_print(self, indent=""):
print(
"%sHelperLowHighPressureRockTransition (%f GPa):"
% (indent, self.transition_pressure)
)
indent += " "
for r in self.rocks:
r.debug_print(indent)
| (self, indent='') |
10,977 | burnman.classes.mineral_helpers | select_rock | null | def select_rock(self):
if self._pressure < self.transition_pressure:
return self.rocks[0]
else:
return self.rocks[1]
| (self) |
10,978 | burnman.classes.mineral_helpers | set_method | null | def set_method(self, method):
for r in self.rocks:
r.set_method(method)
| (self, method) |
10,979 | burnman.classes.mineral_helpers | set_state | null | def set_state(self, pressure, temperature):
Material.set_state(self, pressure, temperature)
self.current_rock = self.select_rock()
self.current_rock.set_state(pressure, temperature)
| (self, pressure, temperature) |
10,982 | burnman.classes.mineral_helpers | unroll | null | def unroll(self):
return self.current_rock.unroll()
| (self) |
10,983 | burnman.classes.mineral_helpers | HelperRockSwitcher |
A Helper that represents a Material that switches between different rocks
based on a user specified select_rock() function based on current temperature
and pressure. This class can be used in several ways:
1. By creating an instance and setting select_rock to a lambda that returns a rock
2. By deriving from this class and implementing select_rock.
| class HelperRockSwitcher(Material):
"""
A Helper that represents a Material that switches between different rocks
based on a user specified select_rock() function based on current temperature
and pressure. This class can be used in several ways:
1. By creating an instance and setting select_rock to a lambda that returns a rock
2. By deriving from this class and implementing select_rock.
"""
def __init__(self):
self.current_rock = None
Material.__init__(self)
def select_rock(self):
raise NotImplementedError("Need to implement select_rock() in derived class!")
def set_method(self, method):
raise NotImplementedError("Need to implement select_rock() in derived class!")
def debug_print(self, indent=""):
print("%sHelperRockSwitcher" % (indent))
def set_state(self, pressure, temperature):
Material.set_state(self, pressure, temperature)
self.current_rock = self.select_rock()
self.current_rock.set_state(pressure, temperature)
def unroll(self):
return self.current_rock.unroll()
@material_property
def molar_internal_energy(self):
return self.current_rock.molar_internal_energy
@material_property
def molar_gibbs(self):
return self.current_rock.molar_gibbs
@material_property
def molar_helmholtz(self):
return self.current_rock.molar_helmholtz
@material_property
def molar_mass(self):
return self.current_rock.molar_mass
@material_property
def molar_volume(self):
return self.current_rock.molar_volume
@material_property
def density(self):
return self.current_rock.density
@material_property
def molar_entropy(self):
return self.current_rock.molar_entropy
@material_property
def molar_enthalpy(self):
return self.current_rock.molar_enthalpy
@material_property
def isothermal_bulk_modulus(self):
return self.current_rock.isothermal_bulk_modulus
@material_property
def adiabatic_bulk_modulus(self):
return self.current_rock.adiabatic_bulk_modulus
@material_property
def isothermal_compressibility(self):
return self.current_rock.isothermal_compressibility
@material_property
def adiabatic_compressibility(self):
return self.current_rock.adiabatic_compressibility
@material_property
def shear_modulus(self):
return self.current_rock.shear_modulus
@material_property
def p_wave_velocity(self):
return self.current_rock.p_wave_velocity
@material_property
def bulk_sound_velocity(self):
return self.current_rock.bulk_sound_velocity
@material_property
def shear_wave_velocity(self):
return self.current_rock.shear_wave_velocity
@material_property
def grueneisen_parameter(self):
return self.current_rock.grueneisen_parameter
@material_property
def thermal_expansivity(self):
return self.current_rock.thermal_expansivity
@material_property
def molar_heat_capacity_v(self):
return self.current_rock.molar_heat_capacity_v
@material_property
def molar_heat_capacity_p(self):
return self.current_rock.molar_heat_capacity_p
| () |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.